- Home /
How to access variable from other class?
Hello. Sorry for that simple question, but I am new to C# and I want to ask: how can I access a variable of a class and modify it in other class. For example:
public class PlayerMovement : MonoBehaviour
{
public bool IsPlayerOnGround;
void Start ()
{
IsPlayerOnGround = false;
}
void Update()
}
public class GroundCheck : MonoBehaviour
{
//I need to access and modify "IsPlayerOnGround" in this class,
//so that it would be changed in PlayerMovement class
}
What I don't get, is that you don't need to create PlayerMovement player = new PlayerMovement() or something in Unity, so I don't know how to change it access it. Can someone explain, why I do not to create an object of the class to put it to Update() and Start() functions and why it works? Thanks!
Answer by smoggach · Feb 10, 2015 at 03:06 PM
Unity uses a component model. Your class exists as a component of whatever GameObject you put it on. All components extend Monobehaviour which provides a reference to the GameObject and many other common components.
If you want to access another class, you have to find a GameObject on which it's resides, and then retrieve it from that GameObject via some manner of GetComponent. And that's only if you have to do it via scripting. It's far easier to make public references.
In your GroundCheck class you would have a public PlayerMovement object. Then in the editor you can drag any object that has a PlayerMovement script into that property on GroundCheck component. Now your groundcheck can just access that.
Unity's really fun that way because your code can be treated like any other asset.
Thank you a lot, smoggach. Your answer really helped me to understand these important basics of Unity and solve my problem. Thanks :)
Your answer
Follow this Question
Related Questions
Can I access variables of scripts that inherit from abstract classes? 2 Answers
[C#] Is there a way to call static variables directly, independent from parent class? 3 Answers
Access to a variable inside a C# class 2 Answers
How to Typecast JS Variables as C# Classes? 0 Answers
how to acess Static variable in other scripts without extended functions? 2 Answers