Accessing variable from other script

点点圈 提交于 2020-01-10 05:35:06

问题


How do I call a variable from other script components?

mirror.transform.position = cop.GetComponent("AI_Car").mirrorPos;

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:


2 things:

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

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!

EDIT: here are the docs




回答2:


You can cast it to the right type:

mirror.transform.position = ((AI_Car)cop.GetComponent("AI_Car")).mirrorPos;
mirror.transform.position = cop.GetComponent<AI_Car>().mirrorPos;

Anyway, the best is to make an AI_Car property, then get it on start, so you can simply read it anywhere in the class by aiCar.mirrorPos or similar.



来源:https://stackoverflow.com/questions/30311674/accessing-variable-from-other-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!