I was reading the Unity scripting guide on this and they suggested using yields and coroutines. However, they mentioned that it doesn't work in an Update or FixedUpdate function and that's exactly where I think I need to use it (I am a beginner, I could be totally wrong).
I'm trying to get a block to randomly choose a direction and go in that direction for a given amount of time. However, for some reason it won't execute the entire turning function (e.g. when I tell it to turn 90 degrees it seems to only turn 3 before randomly choosing another direction). My code thus far looks like this:
Any help would be much appreciated, thank you!
That won't work because you're starting new instances of a coroutine every frame. It would be better to not use Update at all, since it runs every frame and can't be interrupted or delayed. Just to illustrate:
Also, you can use Random.Range instead of Random.value like that, and variables that don't need to be global should always be declared inside functions. (Also it would be better to follow the convention of using uppercase for classes and functions, and lowercase for variables. Plus you should always declare the type for all variables, either explicitly, or implicitly by supplying a value, so "function turn (degrees)" is incorrect; instead it would be "function turn (degrees : float)", and as I mentioned "degrees" should not be a global variable.)
Also, if your intentions are to have the object rotate first, then move, you should yield on the first coroutine instead of having both execute simultaneously. I'd recommend using Lerp as well, instead of Translate and Rotate, since those will result in cumulative accuracy errors over time, especially with low framerates (see MoveObject).