【发布时间】:2019-05-05 19:08:34
【问题描述】:
我在 Unity 的两个不同脚本中有一个名为 gethealth 的变量。我在第一个名为 PlayerController 的脚本中将它创建为静态公共浮点数。当我尝试从另一个脚本(称为 Health)访问它时,它显示的内容完全不同,即使它应该是同一个变量。
我通过在两个脚本中使用 debug.log 来检查它是否相同,并且不知何故它显示了不同的东西。在此过程中的某个地方,它一定发生了变化。
第一个脚本(PlayerController 类,我在其中创建和设置 gethealth 变量):
public float health = 250f;
static public float gethealth;
private void OnTriggerEnter2D(Collider2D col)
{
PlayerLaser missile = col.gameObject.GetComponent<PlayerLaser>();
if (missile)
{
health -= missile.GetDamage();
gethealth = health;
Debug.Log(gethealth);
missile.Hit();
}
}
第二个脚本(健康类):
void Start()
{
Debug.Log(PlayerController.gethealth);
Text myText = GetComponent<Text>();
myText.text = PlayerController.gethealth.ToString();
}
两个 debug.log 显示不同的结果,但它们应该显示相同
【问题讨论】:
-
顺便说一句,以这种方式使用
static不是一个好主意。您应该获得对您的播放器脚本的引用(例如GameObject.Find("Player").GetComponent<PlayerController>())并以这种方式获取其公共health值。