从另一个脚本C#访问变量

Lor*_*eti 8 c# unity-game-engine

你能告诉我如何从另一个脚本访问脚本的变量吗?我甚至已经阅读了统一网站上的所有内容,但我仍然无法做到.我知道如何访问另一个对象而不是另一个变量.

情况就是这样:我在脚本B中,我想X从脚本A访问变量.变量Xboolean.你能帮助我吗 ?

顺便说一句,我需要X在脚本B中大幅更新其值,我该怎么做?在Update功能中访问它如果你可以给我和这些字母的例子将是伟大的!

谢谢

Jay*_*ama 17

首先需要获取变量的脚本组件,如果它们位于不同的游戏对象中,则需要将游戏对象作为参考传递给检查器.

例如,我scriptA.csGameObject AscriptB.csGameObject B:

scriptA.cs

// make sure its type is public so you can access it later on
public bool X = false;
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)