Accessing variable from other script

前端 未结 2 1157
灰色年华
灰色年华 2020-12-21 15:36

How do I call a variable from other script components?

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

It seems that th

相关标签:
2条回答
  • 2020-12-21 16:35

    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

    0 讨论(0)
  • 2020-12-21 16:38

    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.

    0 讨论(0)
提交回复
热议问题