所以我试图通过触摸立方体来更改另一个脚本中的变量。
当前设置
每个人都有自己的剧本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
not private
.
public class ScriptA : MonoBehaviour{
public int playerScore = 0;
void Start()
{
}
public void doSomething()
{
}
}
访问变量playerScore
in ScriptA
from ScriptB
。首先,找到脚本或组件附加到的 GameObjectGameObject.Find
函数然后使用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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)