- Home /
Duplicate Question
How do I access a variable from another GameObject?
I have to objects: the coin, and the player. They each have a script attached to them. The player has a variable called "score". When you click the coin, I want it to add 1 to the score. However, the click function is in the coin script, and the score variable is in the player script. How can I add 1 to the score variable from the coin script?
This is probably the #1 asked question on this list. Google:
"How do I access a variable from another GameObject Unity3d," and you will find lots of hits. Here is one of the best answers to your question:
http://answers.unity3d.com/questions/203054/accessing-a-variable-from-another-script.html
Answer by xboy691 · Oct 19, 2013 at 03:54 AM
//Put this on your character.
//Make a tag called "Coin" and put it on your coin
static var Coin = 0;
function OnTriggerEnter(other : Collider) {
if(other.tag == "Coin") {
Coin += 1;
Destroy(other.gameObject);
}
}
This is what static variables are for, but you really don't need it in this case. Like the other guy said, try looking this up before going to the forums.
Follow this Question
Related Questions
C# to UnityScript conversion help. 0 Answers
UnityScript equivalent of JavaScript objects 2 Answers
Enemy following Player in range 2 Answers
How to make GUI.window appear after button click 1 Answer
Make tranform follow raycast 1 Answer