- Home /
Question by
Tix · Mar 15, 2013 at 06:35 PM ·
Accessing a public variable from another class
Hello everyone,
Here's my problem: I have a gameobject named NPC_1 with a class attached to it, called Character. In this class I have an variable declared like this:
public bool up;
I'm from another class, and I need to access to this variable, knowing the name of the gameobject.
I tried the following:
string name = "NPC_1";
GameObject.Find(name).GetComponent("Character").up = true;
But obviously I'm doing it wrong.
What's the solution to reach the variable?
Thanks for your time.
Comment
Best Answer
Answer by robertbu · Mar 15, 2013 at 06:56 PM
When you call GetComponent() with a string, the type is not known. You can cast the result, or you can change the call to use the form:
GetComponent<Character>();
So your code would be:
GameObject.Find(name).GetComponent<Character>().up = true;