从另一个组件访问变量/函数 [英] Access variables/functions from another Component

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

问题描述

因此,我试图通过触摸多维数据集来更改另一个脚本中的变量. 当前设置

So im trying to change a variable in another script by touching a cube. Current setup

  • 1x播放器
  • 1x敌人

每个都有自己的脚本Enemy_Stats& Character_Stats
如您在这个小片段中所见,这是一个从另一个脚本访问变量的不错的解决方法.

Each with their own script Enemy_Stats & Character_Stats
As you can see in this little snippet it's quite a workaround to access the variable from another script.

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Enemy")
    {
        collision.gameObject.GetComponent<Enemy_Stats>().Health = 
            collision.gameObject.GetComponent<Enemy_Stats>().Health 
            - gameObject.GetComponent<Character_Stats>().AttackDamage;

        if (collision.gameObject.GetComponent<Enemy_Stats>().Health <= 0)
        {
            Destroy(collision.gameObject);
        }
    }
}

我是Unity的新手,但没有一种方法可以像下面这样引用它:
collision.Health?

Iam new to Unity, but isn't there a way to just refer it with something like:
collision.Health?

推荐答案

如何从另一个类访问变量/函数.您要访问或调用的变量或函数必须是public而不是private.

How to access variables/functions from another Class. The variable or function you want to access or called must be public not private.

public class ScriptA : MonoBehaviour{

    public int playerScore = 0;

    void Start()
    {

    }

    public void doSomething()
    {

    }
}

ScriptB访问ScriptA中的playerScore变量.首先,使用GameObject.Find函数找到脚本或组件所连接的GameObject,然后使用GetComponent函数来检索与脚本或组件所连接的脚本或组件.

Access variable playerScore in ScriptA from ScriptB. First, find the GameObject that the script or component is attached to with the GameObject.Find function then use the GetComponent function to retrieve that script or component that is attached to it.

public class ScriptB : MonoBehaviour{

    ScriptA scriptInstance = null;  

    void Start()
    {
      GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
      scriptInstance = tempObj.GetComponent<ScriptA>();

      //Access playerScore variable from ScriptA
      scriptInstance.playerScore = 5;

     //Call doSomething() function from ScriptA
      scriptInstance.doSomething();
    }
}

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

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