坠落物体重力时间间隔

Falling object gravity interval of time

我编写了这段代码,我有 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;
     }
 
 }

他的意图是让物体一个接一个地落下,它们之间有一定的间隔,顺序是随机的。有什么想法吗?

如果你想控制多个对象,并且它们之间有某种关系,通常最好在任何游戏对象上都有一个脚本,并让该脚本处理其他对象。以下示例脚本可以放在任何游戏对象上。

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 组件。