问题
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