- Home /
How to randomly instantiate prefabs after a certain time?
What i want to have is an object(the prefab) falling down randomly( in the x direction) from a certain height. I think i have achieved the script for this correctly, now i want to instantiate each prefab after a certain amount of time say like a random range over a few seconds??
Any help will be appreciated as am a bit of a beginner at this. =)
Answer by Immanuel-Scholz · Apr 21, 2016 at 09:17 AM
So assuming you have the following code to instantiate a prefab immediately:
 void Create()
 {
     // create the new object
     GameObject go = Instantiate(prefab);
     // init some properties of the new object
     go.transform.position = pos;
     go.name = "foo"; 
 }
Then to delay that, you would move it into an own function and call "Invoke" with the functions name and the delay as second parameter.
 void Create()
 {
     // remember to instantiate later
     Invoke("CreateNow", Random.Range(2f, 3f)); // randomly between 2 and 3 seconds
 }
 
 void CreateNow()
 {
     // create the new object
     GameObject go = Instantiate(prefab);
     // init some properties of the new object
     go.transform.position = pos;
     go.name = "foo"; 
 }
 
Answer by sd2992 · Apr 22, 2016 at 05:09 AM
well my code somewhat looks like this now :
using UnityEngine; using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
 public GameObject prefab;
 float xPosition;
 
 void Start () {
     
     xPosition=Random.Range(-10,10);
     Instantiate(prefab, new Vector3(xPosition, 5,-33), Quaternion.identity);
 }
 
 
 void Update () {
 
 }
}
So the invoke functions takes the function name which is instantiating the prefab as it's first parameter and the time range for delay as it's second parameter?
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                