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

查看:49
本文介绍了从另一个脚本 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.

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

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 ?

顺便说一句,我需要在脚本 B 中不断更新 X 的值,我该怎么做?在 Update 函数中访问它如果你能给我和这些字母的例子就太好了!

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.

例如,我在 GameObject A 中有 scriptA.cs,在 GameObject B 中有 scriptB.cs:

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

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

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