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

9
您好,以下是您需要翻译的内容:

请问如何从一个脚本中访问另一个脚本的变量?我已经阅读了Unity官网上的所有内容,但仍然无法做到。我知道如何访问另一个对象,但不知道如何访问另一个变量。

这是情况: 我在脚本B中,想要访问脚本A中的变量X。变量X是一个布尔值。 您能帮我吗?

顺便说一下,在脚本B中,我需要不断更新X的值,该怎么做?在Update函数中访问它。 如果您能给我一个带有这些字母的例子,那就太好了!

谢谢

祝工作愉快!

你能否添加一些你的两个脚本的示例代码?这将有助于为您提供解决方案。 - Jan Thomä
3个回答

18
您首先需要获取变量的脚本组件,如果它们位于不同的游戏对象中,则需要在检查器中将游戏对象作为引用传递。例如,在GameObject A中有scriptA.cs,在GameObject B中有scriptB.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;
}

访问 X 的方式应该是 script.X = true; 而不是 scriptA.X = true; 吗?如果 X 不是 static,那么你不能以那种方式访问它。 - DarkCygnus
1
@GrayCygnus 哎呀,你发现了我的错误。谢谢,我已经修复了它。 - Jay Kazama
如果您引用了GameObject a,那么您也可以直接引用所需的组件,而无需调用GetComponent - derHugo

1
你可以在这里使用静态(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;
 }
}

更多细节,请参考单例类。


1

只是为了完成第一个答案

没有必要

a.gameObject.getComponent<scriptA>();

a 已经是一个 GameObject,所以这样做就可以了

a.getComponent<scriptA>();

如果你要访问的变量在 GameObject 的子元素中,你应该使用:

a.GetComponentInChildren<scriptA>();

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

a.GetComponentInChildren<scriptA>().nameofyourvar;
a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接