gpt4 book ai didi

c# - 从另一个组件访问变量/函数

转载 作者:行者123 更新时间:2023-11-30 13:55:04 25 4
gpt4 key购买 nike

所以我试图通过触摸立方体来更改另一个脚本中的变量。当前设置

  • 1 个播放器
  • 1x 敌人

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

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?

最佳答案

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

public class ScriptA : MonoBehaviour{

public int playerScore = 0;

void Start()
{

}

public void doSomething()
{

}
}

ScriptB 访问 ScriptA 中的变量 playerScore。首先,使用 GameObject.Find 函数找到脚本或组件附加到的 GameObject,然后使用 GetComponent 函数检索附加到它的脚本或组件。

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

关于c# - 从另一个组件访问变量/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com