How do I use variables in a separate script in Unity3D?

巧了我就是萌 提交于 2019-12-14 03:29:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!