Hello, in my scene there are some Transforms who must turn in a random direction when they pass beyond some areas. I made this script.
Do not give me error messages, but the variable choice is constantly changing and the transform turns both right and left. How can I fix it?
asked Apr 27 '11 at 10:06 AM
Hey Hektor, I can see you're new to scripting so one little thing, you say:
When calling a function there is no need for those brackets. You can just leave them out.
Then you have leftRot and rightRot. If your object it out of bounds you constantly pick a random number and then rotate that way. You want to once pick a random number and then constantly rotate that way. Add a boolean that checks if you've done the random picking. So on top of your script put var randomised : boolean = false; and then where if now says
It should say:
answered Apr 27 '11 at 10:43 AM
You should turn leftRot() and rightRot() into Coroutines. The idea is that right now you randomly choose the direction each frame, when what you want is when the object enters the area - decide the direction, and make a method run in that direction until you tell it to stop.
This should give you an idea of how to proceed:
As a side note, you better check OnTriggerStay and the physics of Unity in general, since checking if your object is in the range you want every frame is not efficient at all...
[Edit: I've revised the answer in case someone ever stumbles upon it again. Stupid rookie mistake on my part. Forgetting to add a while loop with a "yield" inside Rotate()... stupid stupid stupid :/]