[JS] Trying to spawn a sprite randomly every second

Hello unity forums!

I am currently trying to figure out how to, as the title said, spawn a sprite in a random location every second. At the moment, the timer that is supposed to count the time in between spawns doesn’t appear to trigger the spawning function when it reaches 1 second like I need it to.

Here’s the code:

#pragma strict

var word : GameObject;
var spawn_position;
var timer = 0.0;

function SpawnWord(){
Debug.Log("Spawning");
spawn_position = Vector2(Random.Range(1,800),Random.Range(1,800));
var tempspawnword = Instantiate(word, spawn_position, Quaternion.identity);
}

function Start () {

}

function Update () {
timer += Time.deltaTime;
if(timer >= 1.0)
    {
    SpawnWord();
    timer = 0.0;
    }
}

Also if I’m doing anything else wrong here that won’t work, please let me know, I’m still pretty new to javascript! (Normally I would be asking on the Unity Answers page, but it won’t let me create any new questions :/)

Have you tested the function itself? Does it work?

Edit: There is no need to leave a function Start() if you don’t write anything inside.

Thanks for this, I can’t believe I didn’t try the function by itself. It did not seem to work, so I ended up re-writing everything and had it work this time.

Here’s the code if anyone ends up finding this and needs something to reference:

private var wordClone : GameObject;
var word : GameObject;
var wordX;
var wordY;
private var wordPosition;
var timer = 0.0;

function Update () {
    wordX = Random.Range(-5.0, 5.0);
    wordY = Random.Range(-5.0, 5.0);
    wordPosition = Vector3(wordX, wordY, transform.position.z);
  
    timer += Time.deltaTime;
    if(timer >= 1.0)
    {
        Debug.Log("spawning");
        Spawnword();
        timer = 0.0;
    }
}
function Spawnword ()
{
    wordClone = Instantiate(word, wordPosition, transform.rotation);
}
1 Like

Use InvokeRepeating instead.

–Eric

1 Like

Eric is right. Use invokeRepeating. It will save you tons of time!

Thanks, this helps a lot!