Trying to write a script to do something every 1 second

Hi everyone!

I’m trying to write a script that will instantiate a balloon object randomly. I have my script randomly generating a number between 1 and 20 every 1 second, and if that number is 20, spawn a balloon. However, I can’t even get the “every 1 second” part to work! Can anyone point me towards what I’m doing wrong? (probably more than one thing! :smiley: )

using UnityEngine;
using System.Collections;

public class BalloonEscape : MonoBehaviour {

	private int m_Escape;

	private void Update() {
		float balloontime = Time.deltaTime;
		balloontime += Time.deltaTime;
		
		if (balloontime >= 1f)
		{
			Randomness();
			Debug.Log("balloontime is" + "" + balloontime);
			balloontime = 0f;
		}
	}
	
	void Randomness()
	{
		m_Escape = Random.Range(1,20);
		Debug.Log("m_Escape is" + "" + m_Escape);
		if (m_Escape == 20)
		{
			//do stuff here
			Debug.Log("Balloon Away!");
		}
	}
}
2 Likes

Thank you once again!

Are there any performance hits for using this method? I know infinite while loops can have really bad effects on frame rate. Does this method have any similar problems?

I don’t think you’d find Update() in nearly every Unity scripting example, and in the script templates, if an “infinite while loop” had the effect you’re talking about. :wink:

(An actual infinite loop e.g.

while (true) //no yield instruction here

will actually be a problem.)

That was exactly what I was looking for tkx

This post was necro’d so hard the database holding it had to be necro’d to fetch it.

2 Likes

You are creating a new variable called “balloon time” evey frame and setting it to time.deltatime, you need to declare it outside of any method and only add time.Delta time to it, don’t forget to reset it to zero when you spawn a balloon.

Using a coroutine with “yield return new wait for seconds(60)” or “invoke(” blah",60)" is much better

Invoke(string) is very 2010. State of the art, back then, in method calling technology.