Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

unity3d - Accessing variable from other script

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'.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...