问题
Title explains it all, I want to know how to access variables from another script. I've searched online, but found nothing that's worked.
回答1:
You could make a class
, instantiate an object
of the class and access propterties.
Or you could use static
variables.
Or even beter, lets say you have a GameManager.cs
script attached to an empty object called GameManager. And you want to access its variables form the LevelManager.cs
script. You do this inside the LevelManager.cs
public GameManager gameManager;
Then you can drag and drop your GameManager empty object to this public field, and everytime you want to access a variable you type gamemanager.yourVariableHere
Or, if you dont want to drag and drop:
in the start method...
void Start()
{
gameManager = GameObject.Find("GameManager");
//this way it finds your object automatically
}
Hope it helped, good luck.
回答2:
First you need to make your variables public. Then get the GameObject, get the Componend and access your variable.
var variable = GameObject.Find("name").GetComponent<ScriptClass>().yourVariable;
回答3:
To add to the previous answer, if your class is a pure c# class and doesnt inherit from monbehaviour then must create an instance of class. If you want global access to certain variables you should look into static variables or implement a singleton pattern
来源:https://stackoverflow.com/questions/33113980/how-do-i-use-variables-in-a-separate-script-in-unity3d