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
1.2k views
in Technique[技术] by (71.8m points)

unity3d - Accessing a variable from another script C#


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

1 Reply

0 votes
by (71.8m points)

You first need to get the script component of the variable, and if they're in different game objects, you'll need to pass the Game Object as a reference in the inspector.

For example, I have scriptA.cs in GameObject A and scriptB.cs in GameObject B:

scriptA.cs

// make sure its type is public so you can access it later on
public bool X = false;

scriptB.cs

public GameObject a; // you will need this if scriptB is in another GameObject
                     // if not, you can omit this
                     // you'll realize in the inspector a field GameObject will appear
                     // assign it just by dragging the game object there
public scriptA script; // this will be the container of the script

void Start(){
    // first you need to get the script component from game object A
    // getComponent can get any components, rigidbody, collider, etc from a game object
    // giving it <scriptA> meaning you want to get a component with type scriptA
    // note that if your script is not from another game object, you don't need "a."
    // script = a.gameObject.getComponent<scriptA>(); <-- this is a bit wrong, thanks to user2320445 for spotting that
    // don't need .gameObject because a itself is already a gameObject
    script = a.getComponent<scriptA>();
}

void Update(){
    // and you can access the variable like this
    // even modifying it works
    script.X = true;
}

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

...