Accessing variable from other script

2019-01-28 14:12发布

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'.

2条回答
我命由我不由天
2楼-- · 2019-01-28 15:07

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.

查看更多
3楼-- · 2019-01-28 15:09

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

查看更多
登录 后发表回答