- Home /
using yield in components
hello, i was wondering does someone can help me with the code i am using. i am using this code in a lot of places in my game:
function ZoomIn(distance : float,endDistance : float){
var t = 0.0; while (t<1.0){
t+=Time.deltaTime *(1.0/0.2);
cam.distance=Mathf.Lerp(distance,endDistance,t);
yield;
}
}
the question is how to structure the code, so that i can make this a separate script and use it as a component? is there a way to use it like this:
cam.distance=ZoomComponent.ZoomIn(cam.distance,endDistance);
ZoomComponent being the reference to the script where ZoomIn function is. sorting this out would be from great help!
Answer by Eric5h5 · Aug 06, 2010 at 04:16 PM
Since ZoomIn is a coroutine, you can't return a value that can be assigned to cam.distance. A way around this is to use a reference value, so the value you pass in is modified inside the coroutine. This is a little tricky, since while you can use reference values in Javascript, you can't declare them, and even in C#, you can't declare reference values directly when using IEnumerators (coroutines). A way around that is to use a custom class, since classes are always reference values:
function ZoomIn (refFloat : RefFloat, start : float, end : float, speed : float) {
var t = 0.0;
while (t < 1.0) {
t += Time.deltaTime * speed;
refFloat.a = Mathf.Lerp(start, end, t);
yield;
}
}
class RefFloat { var a : float;
function RefFloat (a : float) {
this.a = a;
}
}
You can use it like this:
function Start () { var foo = new RefFloat(0.0); var zoomScript : Zoom = GetComponent(Zoom); zoomScript.ZoomIn(foo, 0.0, 1.0, .5);
while (true) {
Debug.Log (foo.a);
yield;
}
}
So you can see that the "foo" variable is changed by the function. In your case, the "distance" variable would have to be changed from a float to a RefFloat, and you would access it by using "cam.distance.a" instead of "cam.distance".
Answer by Jens T · Aug 06, 2010 at 03:51 PM
Your ZoomIn function does not return a value, so you cannot do this.
What i suppose you are modifying is the camera position, so all you ZoomComponents need to be able to access the camera. I think the best way is to pass the world X,Y,Z values of your object (or better yet, the Transform of the GameObject you are zooming on) and then have the zoomComponent modify the the camera position. The reference to the camera should be made by creating a variable like this in the zoomComponent.
var camera:GameObject
and then dragging the MainCamera onto this scriptComponent in the inspector. (You can also get it by camera = GameObject.Find("MainCamera").
Take care however, that there is not multiple zoomComponents affecting the single camera simoultainously. You can solve this by static variables.
I am quite new to Unity, so dont take me for a pro. Hope I can be of help.