从其他脚本访问变量 [英] Accessing variable from other script
问题描述
如何从其他脚本组件中调用变量?
How do I call a variable from other script components?
mirror.transform.position = cop.GetComponent("AI_Car").mirrorPos;
似乎无法访问在脚本AI-Car-script
中声明的公共变量carPos
:
It seems that the public variable carPos
declared in the script AI-Car-script
cannot be accessed:
'mirrorPos' is not a member of 'UnityEngine.Component'.
推荐答案
两件事:
1)我使用C#工作,所以我对此可能是错的,但是我认为您必须获取组件,然后获取变量.例如:
1) I work in C#, so I may be wrong about this, but I think you have to get the component and THEN get the variable. For example:
var otherScript: OtherScript = GetComponent("AI_CAR");
var newPosition = otherScript.mirrorPos;
2)我认为最好的做法是先创建一个临时变量,然后再访问它.因此,在上面的示例中,我将像这样更改mirror.transform.position:
2) I think it's best practice to make a temporary variable and then access it. So in the above example, I would then change mirror.transform.position like this:
mirror.transform.position = newPosition;
显然,在vars中工作并不总是很好(有时是完全不同的对话),但这只是一个简单的伪代码示例.希望这会有所帮助!
Obviously it's not not always great to work in vars (sometimes it is, that's an entirely different conversation) but this is just a simple pseudocode example. Hope this helps!
此处是文档
这篇关于从其他脚本访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!