从另一个脚本C#访问变量 [英] Accessing a variable from another script C#

查看:708
本文介绍了从另一个脚本C#访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何从另一个脚本访问脚本的变量?我甚至已经阅读团结一切网站,但我还是无法做到这一点。我知道如何访问另一个对象而不是另一个变量。

Can you tell me how to access a variable of a script from another script ? I have even read everything in unity website but I still can’t do it. I know how to access another object but not another variable.

这是这种情况:
我在脚本中的我要访问的变量 X 是来自脚本的 A 。变量 X 布尔
你能帮助我吗?

This is the situation : I’m in script B and I want to access the variable X from script A. The variable X is boolean. Can you help me ?

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

Btw i need to update X’s value costantly in script B , how do I do that ? Access it in Update function If you could give me and example with these letters would be great !

感谢您

推荐答案

您首先需要获得变量的脚本部件,如果他们在不同的游戏对象,你需要通过游戏对象为在检查的参考。

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.

例如,我有 scriptA.cs 游戏物体A scriptB.cs 游戏物体乙

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;
}

这篇关于从另一个脚本C#访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆