您能告诉我如何从另一个脚本访问脚本的变量吗?我甚至已经阅读了统一网站上的所有内容,但我仍然无法做到。我知道如何访问另一个对象而不是另一个变量。
情况如下:
我在脚本 B ,我想从脚本 A 访问变量X
。变量X
为boolean
。
你能救我吗?
顺便说一下,我需要在脚本 B 中更新X
的值,我该怎么做?在Update
函数中访问它
如果你能给我这些字母的例子会很棒!
谢谢
答案 0 :(得分:17)
首先需要获取变量的脚本组件,如果它们位于不同的游戏对象中,则需要将游戏对象作为参考传递给检查器。
例如,我scriptA.cs
中的GameObject A
和scriptB.cs
中的GameObject B
:
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;
}
答案 1 :(得分:1)
只是为了完成第一个答案
不需要
a.gameObject.getComponent<scriptA>();
a
已经是GameObject
所以这样做
a.getComponent<scriptA>();
如果您尝试访问的变量位于GameObject
的子级中,则应使用
a.GetComponentInChildren<scriptA>();
如果您需要它的变量或方法,您可以像这样访问它
a.GetComponentInChildren<scriptA>().nameofyourvar;
a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams);
答案 2 :(得分:1)
你可以在这里使用静态。
这是一个例子:
<强> 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;
}
}
OR
<强> 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类。