Search code examples
unity-game-engine2dunityscript

Infinite prefab spawn bug


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);
    }
}

Solution

  • 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.