【问题标题】:Static variable changes between different scripts in Unity?Unity中不同脚本之间的静态变量变化?
【发布时间】: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&lt;PlayerController&gt;())并以这种方式获取其公共 health 值。

标签: c# unity3d static


【解决方案1】:

您问为什么它显示不同的东西,但您提供的代码告诉我们它应该显示不同的东西。在 Health Class 上,您在 Start 上记录 PlayerController.gethealth。 (有关启动方法的文档请参阅:https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html

在 PlayerController 上,您正在记录 gethealth 在减少您的健康并重新分配它之后。

除非代码的某些部分丢失,否则Health 类会记录一个 0,即浮点数的默认值。之后 PlayerController 记录一个小于 250 的数字 (250 - missile.GetDamage())。每次调用 OnTriggerEnter2D 时都会发生此日志记录,从而减少显示的数量。

您可能想要的是在 Awake 方法中设置 gethealth 属性(请参阅之前的文档链接),这样

Awake() { gethealth = health; }

【讨论】:

  • 谢谢,这帮助我解决了这个问题。我使用了更新函数而不是 Awake,并初始化了 Health 中的浮点数,使其不记录 0。
猜你喜欢
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 2018-05-22
  • 2012-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多