- Home /
What's wrong with my script?
Here's the script.
#pragma strict
var enemy : Transform;
private var spawnArea : Vector2;
private var canSpawn : boolean = true;
function Update () {
if (canSpawn == true) {
Instantiate (enemy, spawnArea, Quaternion.identity);
canSpawn = false;
WaitForSeconds(Random.Range(0, 3));
canSpawn = true;
}
}
I want it to spawn every 0-3 seconds but it ends up spawning every frame. Any help?
Thanks in advance.
Answer by taxvi · Dec 29, 2014 at 10:15 AM
the WaitForSeconds is a special instruction used only in co-routine functions, google for more info. it won't work in Update function. what you need is a simple timer implementation.
#pragma strict
var enemy : Transform;
private var spawnArea : Vector2;
public var spawnTime : float = 3f;
private var timer : float = 0f;
function Update () {
if (timer > spawnTime) {
Instantiate (enemy, spawnArea, Quaternion.identity);
timer = 0f;
//another note here:
//if you don't add 'f' at the end of the numbers, unity will take them as integers
//and return a random integer between 0, 3.
//this will return random float:
spawnTime = Random.Range(0f, 3f);
}
timer += Time.deltaTime;
}
This might make me sound stupid (I'm kinda new to Unity) but what's the "f" next to the numbers for? @taxvi
Oh xD should've read the notes. You said what it was there
and it can take decimal values like 4.95, while integers can not
@Chickenator Yes, what you said is correct. But when it comes to numbers with a decimal point, there are 3 types:
float, double, decimal
The difference is the precision (how many digits you can have in the number).
float is 32 bits
double is 64 bits
decimal is 128 bits
$$anonymous$$ore info here: http://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx
Your answer
Follow this Question
Related Questions
How to Spawn after checking if the clones are destroyed. 1 Answer
Have a spawning issue on iOS 0 Answers
Prevent object from spawning at a spawn point twice in a row? 3 Answers
Losing references after reloading the scene, even though they exist again. 1 Answer
how to destroy a object only in game and not the prefab 2 Answers