I want to read a string variable from another class like this:
public class Startmenu : MonoBehaviour {
public string myText; //
I want to use the content of this variable myText, from this class Startmenu in another class
public class Move : MonoBehaviour {
// Use this for initialization
void Start () {
}
I want to read the variable string myText from Startmenu class in Move class, nothing too complicated just get that string so I can use it to name something in the class Move
You can read any public variable of a class from any other class. In your case
public class StartMenu : MonoBehaviour {
public string myText;
void Start()
{
//
}
void Update()
{
//
}
}
You can access StartMenu’s field called myText as seen here in the Start function:
public class Move : MonoBehaviour {
public StartMenu startMenuReference; // in Inspector drag and drop here the obejct that holds the StartMenu component
void Start()
{
if (startMenuReference == null)
Debug.LogError("Start Menu not given"); // just remind yourself to fill the slot.
else
Debug.Log(startMenuReference);
}
void Update()
{
}
}
And that’s the most straight forward.
If you are sure you’ll always have just one StartMenu instance you can use the static instance method that many developers use in many occasions.
It looks like this:
public class StartMenu : MonoBehaviour {
public string myText;
public static StartMenu instance;
void Awake() // note it's now Awake instead of Start. That's important.
{
instance = this; // hold a reference to the (last) instance of this class
}
void Update()
{
//
}
}
And in that case your Move class would change as follows:
public class Move : MonoBehaviour {
StartMenu startMenuReference; // in Inspector drag and drop here the obejct that holds the StartMenu component
void Start()
{
startMenuReference = StartMenu.instance;
if (startMenuReference == null)
Debug.LogError("Start Menu does not exist"); // No instances found
else
Debug.Log(startMenuReference);
}
void Update()
{
//
}
}
Go back to Unity, and click on the object that has this script attached. In the inspector, you’ll see a space where you can drag a gameobject that has the Startmenu script attached to. If you drag the game object, it’ll automatically put the script into the box.
It’s totally fine for you to then manipulate startmenu.myText – BUT good coding practice usually says that you should make your variables private and use getters and setters to access them. So you might have something like: