Unity 声称我没有对象引用



它给出了第14行和第26行的错误。我不明白,我只是在第8行创建了对象

第一个是运行healthpoint obj的代码,第二个是声称我没有对象引用的代码。

using UnityEngine;
public class HealthPoint
{
public float max;
public float min = 0;
public float current;
}

/

using UnityEngine;
public class Obstacle : MonoBehaviour
{
[SerializeField] private float MaxHp = 100;
[SerializeField] private float MinHp = 0;

private HealthPoint hp;

SpriteRenderer spriteRenderer;

private void Start()
{
hp.max = MaxHp;
hp.min = MinHp;
hp.current = MaxHp;
}

public void GotHit(float HitPoint)
{
hp.current -= 20;
}

private void Update()
{
float color = (int)(hp.current / 100);
spriteRenderer.color = new Color(color, color, color);
}
}

我声明了它,但没有初始化它。我需要为声明的var.分配一个对象

using UnityEngine;
public class Obstacle : MonoBehaviour
{
[SerializeField] private float MaxHp = 100;
[SerializeField] private float MinHp = 0;
private HealthPoint hp;
private SpriteRenderer spriteRenderer;
private void Start()
{
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
hp = new HealthPoint();
hp.max = MaxHp;
hp.min = MinHp;
hp.current = MaxHp;
}
public void GotHit(float HitPoint)
{
hp.current -= HitPoint;
}
private void Update() //health decrees will have an another effect
{
float color = hp.current / 100;
spriteRenderer.color = new Color(color, color, color);
}
}

替换

private HealthPoint hp;

带有

private HealthPoint hp= new HealthPoint();

此处的以下问题:

由于尚未创建对象的实例,因此您将获得一个null引用。在第一个声明中或在等启动函数中添加HealthPoint hp = new HealthPoint();

public void Start(){
hp = new HealthPoint();
...
}

将修复您的错误。然而,我认为您正在使用start函数作为构造函数,这可能会起作用,但至少是奇怪的

更好的约定是编辑HealthPoint类并在其中添加构造函数。例如

public HealthPoint(float maxHp, minHp, currentHp) {
this.max = maxHp;
this.min = minHp;
this.current = currentHp;
}

在这一点上,你也可以从类中删除Monoactivity扩展,除非你以后需要它

public class HealthPoint : Monobehaviour 

->

public class HealthPoint

现在,一旦你有了构造函数,你就可以在Start()函数中这样做

HealthPoint hp = new HealthPoint(MaxHp, MinHp, MaxHp); 
// passing maxhp as the current hp because I am assuming you start with max hp

相关内容

  • 没有找到相关文章

最新更新