I made this code where I have 8 objects and each object has this script, where between a random time interval the objects drop randomly
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;
}
}
what he intended was for the objects to fall one by one with an interval between them in a random order. any ideas?
CodePudding user response:
If you want to control several objects, and they have some relation to each other, it is usually best to have one script on any GameObject, and let that script handle the other objects. The following example script can be placed on any GameObject.
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!");
}
}
You then have to add references to the objects you want to drop in the scene editor. It should look something like this (I have added four cylinders). Note that the objects you try to add must of course already have a Rigidbody component on them.