0

I have a simple spawn script for my 2D game that i wrote, that i want to spawn an object after a specific period of time. I managed to get this to work but the one problem is that the object keeps spawning. I just want the object to spawn once not an infinite amount.

var myTimer : float = 5.0; var thePrefab : GameObject; function Update () { if(myTimer > 0){ myTimer -= Time.deltaTime; } if(myTimer <= 0){ var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation); } } 
2

1 Answer 1

1

By shifting around your if statements, you can restrict your object to only spawning once:

var myTimer : float = 5.0; var thePrefab : GameObject; function Update () { if(myTimer > 0){ myTimer -= Time.deltaTime; if(myTimer <= 0){ var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation); } } } 

Now, the object will only spawn if myTimer > 0 prior to the decrement, and myTimer <= 0 following the decrement - which only happens once.

Hope this helps! Let me know if you have any questions.

Sign up to request clarification or add additional context in comments.

6 Comments

Great! I'm glad I could help you out.
While it is totally admirable to help new Unity hobbyists, consider there is a HUGE problem with clutter in the Unity3D tag here. Indeed it is becoming very difficult to get questions seen or answered. Consider it's often best to just close the question, perhaps leaving a helpful comment if necessary
@JoeBlow Ah, gotcha. Although not certain the suggested duplicate is applicable in this case - the error was in the OP's code logic, and not on being able to set a parent for their game object.
hi @serlite. One thing is, don't forget, use any close reason you like. Nobody really looks at or cares about close reasons much. This could also be closed as "caused by a simple typographical error" "too vague" and more.
@JoeBlow Oh, huh...I try to use my close votes wherever I can (I agree that the Unity3D tag is a bit of a cesspool of low-quality/effort questions), but I suspect our close-voting heuristics differ somewhat, haha.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.