从另一个脚本访问variablesC#

你能告诉我如何从另一个脚本访问脚本的variables? 我甚至在团结网站上看过所有的东西,但我仍然无法做到。 我知道如何访问另一个对象,而不是另一个variables。

这是情况:我在脚本B ,我想从脚本A访问variablesX variablesXboolean 。 你可以帮我吗 ?

顺便说一句,我需要在脚本B中更新X的值,我该怎么做? 在Update函数中访问它如果你能给我和这些字母的例子将是伟大的!

谢谢

您首先需要获取variables的脚本组件,如果它们位于不同的游戏对象中,则需要在检查器中传递游戏对象作为参考。

例如,我在scriptA.cs GameObject AscriptA.csscriptB.cs GameObject BscriptA.cs

scriptA.cs

 // make sure its type is public so you can access it later on public bool X = false; 

scriptB.cs

 public GameObject a; // you will need this if scriptB is in another GameObject // if not, you can omit this // you'll realize in the inspector a field GameObject will appear // assign it just by dragging the game object there public scriptA script; // this will be the container of the script void Start(){ // first you need to get the script component from game object A // getComponent can get any components, rigidbody, collider, etc from a game object // giving it <scriptA> meaning you want to get a component with type scriptA // note that if your script is not from another game object, you don't need "a." // script = a.gameObject.getComponent<scriptA>(); <-- this is a bit wrong, thanks to user2320445 for spotting that // don't need .gameObject because a itself is already a gameObject script = a.getComponent<scriptA>(); } void Update(){ // and you can access the variable like this // even modifying it works script.X = true; } 

只是为了完成第一个答案

不需要a.gameObject.getComponent<scriptA>();
a已经是一个游戏对象,所以这样做
a.getComponent<scriptA>();
如果你试图访问的variables是在游戏对象的子a.GetComponentInChildren<scriptA>();你应该使用a.GetComponentInChildren<scriptA>();
如果你需要一个variables或方法,你可以像这样访问它
a.GetComponentInChildren<scriptA>().nameofyourvar; a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams);

你可以在这里使用static。

这里是例子:

ScriptA.cs

 Class ScriptA : MonoBehaviour{ public static bool X = false; } 

ScriptB.cs

 Class ScriptB : MonoBehaviour{ void Update() { bool AccesingX = ScriptA.X; // or you can do this also ScriptA.X = true; } } 

有关更多详细信息,请参阅单例类。