我制作了這段代碼,其中有 8 個物件,每個物件都有這個腳本,在隨機時間間隔之間,物件隨機掉落
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cylinderFallv2 : MonoBehaviour
{
private Rigidbody temp;
// Start is called before the first frame update
void Start()
{
temp = GetComponent<Rigidbody>();
StartCoroutine(waitTime());
}
public IEnumerator waitTime() {
temp.useGravity = false;
float wait_time = Random.Range (3.0f;, 12.0f;);
yield return new WaitForSeconds(wait_time);
temp.useGravity = true;
}
}
他的目的是讓物體一個一個地落下,它們之間有一個隨機的間隔。有任何想法嗎?
uj5u.com熱心網友回復:
如果您想控制多個物件,并且它們彼此之間存在某種關系,通常最好在任何游戲物件上都有一個腳本,并讓該腳本處理其他物件。以下示例腳本可以放置在任何游戲物件上。
using System.Collections;
using System.Linq;
using UnityEngine;
public class RandomFall : MonoBehaviour
{
public Rigidbody[] rigidbodies;
public float minTime = 3.0f;
public float maxTime = 12.0f;
private void Start()
{
foreach (Rigidbody rigidbody in rigidbodies)
rigidbody.useGravity = false;
StartCoroutine(dropRandomly());
}
public IEnumerator dropRandomly()
{
foreach (var rigidbody in rigidbodies.OrderBy(r => Random.value))
{
float wait_time = Random.Range(minTime, maxTime);
Debug.Log($"Waiting {wait_time:0.0} seconds...");
yield return new WaitForSeconds(wait_time);
Debug.Log($"Dropping {rigidbody.name}...");
rigidbody.useGravity = true;
}
Debug.Log("All dropped!");
}
}
然后,您必須添加對要放入場景編輯器中的物件的參考。它應該看起來像這樣(我添加了四個氣缸)。請注意,您嘗試添加的物件當然必須已經具有 Rigidbody 組件。

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397772.html
