从另一个组件访问变量/函数 [英] Access variables/functions from another Component
问题描述
因此,我试图通过触摸多维数据集来更改另一个脚本中的变量. 当前设置
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屋!