从另一个脚本C#访问变量

本文关键字:访问 变量 脚本 另一个 | 更新日期: 2023-09-27 18:22:25

你能告诉我如何从另一个脚本访问脚本的变量吗?我甚至读过unity网站上的所有内容,但我仍然做不到。我知道如何访问另一个对象,但不知道如何访问其他变量。

情况如下:我在脚本B中,我想从脚本A访问变量X。变量Xboolean。你能帮我吗?

顺便说一句,我需要在脚本B中同时更新X的值,我该怎么做?在Update功能中访问如果你能用这些信给我举个例子,那就太好了!

感谢

从另一个脚本C#访问变量

首先需要获取变量的脚本组件,如果它们位于不同的游戏对象中,则需要将游戏对象作为引用传递到检查器中。

例如,我在GameObject A中有scriptA.cs,在GameObject B:中有scriptB.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已经是GameObject,所以这将进行

a.getComponent<scriptA>();

如果您试图访问的变量在GameObject的子级中,则应该使用

a.GetComponentInChildren<scriptA>();

如果你需要它的变量或方法,你可以像这个一样访问它

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;
 }
}

ScriptA.cs

Class ScriptA : MonoBehaviour{
//you are actually creating instance of this class to access variable.
 public static ScriptA instance;
 void Awake(){
     // give reference to created object.
     instance = this;
 }
 // by this way you can access non-static members also.
 public bool X = false;

}

ScriptB.cs

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

有关更多详细信息,可以参考singleton类。