从另一个脚本C#访问变量你能告诉我如何从另一个脚本访问脚本的变量吗?我甚至已经阅读了统一网站上的所有内容,但我仍然无法做到。我知道如何访问另一个对象而不是另一个变量。情况就是这样:我在脚本B中,我想X从脚本A访问变量。变量X是boolean。你能帮助我吗 ?顺便说一句,我需要X在脚本B中大幅更新其值,我该怎么做?在Update功能中访问它如果你可以给我和这些字母的例子将是伟大的!谢谢
3 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
首先需要获取变量的脚本组件,如果它们位于不同的游戏对象中,则需要将游戏对象作为参考传递给检查器。
例如,我scriptA.cs
在GameObject A
和scriptB.cs
在GameObject B
:
scriptA.cs
// make sure its type is public so you can access it later onpublic 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 therepublic scriptA script; // this will be the container of the scriptvoid 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;}
红颜莎娜
TA贡献1842条经验 获得超12个赞
只是为了完成第一个答案
没有必要
a.gameObject.getComponent<scriptA>();
a
已经是一个GameObject
所以这样做了
a.getComponent<scriptA>();
如果您尝试访问的变量是GameObject
您应该使用的子项
a.GetComponentInChildren<scriptA>();
如果您需要它的变量或方法,您可以像这样访问它
a.GetComponentInChildren<scriptA>().nameofyourvar;a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams);
手掌心
TA贡献1942条经验 获得超3个赞
你可以在这里使用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类。
- 3 回答
- 0 关注
- 1285 浏览
添加回答
举报
0/150
提交
取消