- Home /
Vars from different functions
A rather general question.
I have a var in my OnMouseDrag function. I calculate it, it works.
Then I refer to it in my OnMouseUp — it says it doesnt know what I am talking about.
I guess it has something to do with the function type...
Do you know what scope is in program$$anonymous$$g terms?
public var object : Transform;
function On$$anonymous$$ouseDrag () {
player = GameObject.FindWithTag("Player").transform;
transform.LookAt (player);
public var distance : float = Vector3.Distance(object.transform.position, player.transform.position);
}
function On$$anonymous$$ouseUp ()
{
rigidbody.AddForce(Vector3(distance * 50,distance * 40,0));
}
here`s my code; I don`t know what scope is in progra$$anonymous$$g terms.
Answer by Cains · Nov 04, 2013 at 09:51 AM
Your problem is indeed the scope of your variable distance. Because you declare the variable in the OnMouseDrag() function, the variable only exists within that function. So once that function ends the variable basically doesn't exist.
public var object : Transform;
public var distance : float;
function OnMouseDrag () {
player = GameObject.FindWithTag("Player").transform;
transform.LookAt (player);
distance = Vector3.Distance(object.transform.position, player.transform.position);
}
function OnMouseUp () {
rigidbody.AddForce(Vector3(distance * 50,distance * 40,0));
}
This should work for you. By declaring distance outside the functions you can now use it anywhere in that script.
Another tip is it's not good practice to name variables with names used by the engine. Although I don't think it's actually causing you any problems, you declared a variable named object which is also a type of variable (that's why it's in blue), you should probably name it something else.
Also, I see that player is never declared but I'm sure it is in your actual code. How you have it now everytime they drag the mouse it's going to assign the Player GameObject to player, which will mean it will happen many times even though you only need to do it once. You should declare it in Start() like below
public var player : Transform;
function Start() {
player = GameObject.FindWithTag("Player").transform;
}
Finally, I'm fairly sure you don't need to declare your variables as public as this is done by default, so you only need to declare them as "var distance : float;".