- Home /
Maths with variables
I'm trying to get it to instantiate an object every time a ball hits a bucket, and when there are no more balls left to instantiate something else. Here is the script...
var total : float = 2; var firework : GameObject; var celebration : GameObject;
function OnCollisionEnter(theCollision : Collision){ if(theCollision.gameObject.name == "Bucket"){ print (total--); var instance : GameObject = Instantiate(firework, transform.position, transform.rotation);
} }
function Update(){ if (total = 0); var instance : GameObject = Instantiate(celebration, transform.position, transform.rotation); }
Any ideas?
One problem now, is that the celebration instantiates when ONE ball hits the bucket. (e.g. when total == 1). I want it to be after both (obviously.) I've moved it to the OnCollisionEnter section, and sorted out all the other problems.
Answer by DaveA · Mar 23, 2011 at 09:22 PM
if (total = 0);
You probably want
if (total == 0) two = signs, no semicolon
When you fix that, it will instantiate one of those things every frame as long as total == 0, which is probably NOT what you want. You should instantiate when the determination is made, or otherwise set a boolean variable or something saying that you have instantiated that object, so as to avoid doing it again every frame.
Check that the let us know
Of course... I feel so stupid now. Haven't checked it but sure it works.
But wait, there's more! I would not trust print (total--) to do the right thing (although it might). Will it decrement the total THEN print it, or print it then decrement it? I think you can lose the entire Update function, and modify the other func to check for total==0 before doing the instantiate. Also make sure fireworks is assigned (presumably in the Inspector)
@Jessy: no, that would be --total. total-- will print the total then decrement it.
Which is why I usually opt for breaking it into separate statements: total--; print (total);
Answer by Jessy · Mar 23, 2011 at 09:27 PM
Use ints. Floats are not really suitable for equality comparisons. Also, once you get that working, your current code is going to instantiate celebration continuously. Move that code to the Collision.
I was just about to ask that... I can't give this as correct too, but I'll vote it up.
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
On Button press Move Value toward 2 Answers
Gun Script Help 2 Answers
How to use Enum? 1 Answer