Hi I have a problem where I am trying to change the speed of a transforming object upon a button press. The speed variable is changing and the debug text fires, but the speed does not actually affect the object until it reaches its destination on the transform and starts again. How do I make it so that the objects speed will change and update with the key press at realtime?
Script on the object:
var Racer2Dest : Vector3;
var speed : int;
function Start () {
var PlaneStart = transform.position;
speed = 10;
while (true) {
yield MoveObject(transform, PlaneStart, Racer2Dest, speed);
}
}
function MoveObject (thisTransform : Transform, startPos : Vector3, endPos : Vector3, time : float) {
var i = 0.0;
var rate = 1.0/time;
while (i < 1.0) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield;
}
}
Instead of just calculating the rate variable once before the loop in the MoveObject function, you could make the rate a global variable, and make another function (call it, say, RateChange) in that script to recalculate the rate. So instead of GetComponent(Racer2_path).speed = 5;, you would do GetComponent(Racer2_path).RateChange(5);.
I am not sure exactly how context of a coroutine is generated. Here context mean association
of local and global variables with process space of a coroutine. Usually, a function and local variables declared
within the function generates a thread context. Thread terminates when associated function returns.My possible
guess is, speed parameter in MoveObject() is passed once by value, when you yield this function.You are changing
speed globally while MoveObject() is still in execution. So, your change has no effect on time parameter of MoveObject().
Probably, thats why you need to wait until next execution MoveObject(). This time you get your speed updated.Here is my
solution, receive speed directly in while loop of MoveObject(), So that you don’t need wait.
var Racer2Dest : Vector3;
var speed : float;
function Start () {
var PlaneStart = transform.position;
speed = 1000;
while (true) {
yield MoveObject(transform, PlaneStart, Racer2Dest, speed);
}
}
function MoveObject (thisTransform : Transform, startPos : Vector3, endPos : Vector3, time : float) {
var i: float = 0.0;
while (i < 1.0) {
//use speed globally instead of using parameter time
var rate: float = 1.0/speed;
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield;
}
Be careful with your while loops. If you’re continuously calling MoveObject from Start, and that MoveObject’s while loop makes the lerp happen many times every time it’s called, you’re not going to get a clean speed update.
Then, be also wary of gameObject.find in an update loop. Should not be called every frame (cache for performance).