【问题标题】:Unity null exception when Instantiating class实例化类时的Unity空异常
【发布时间】:2021-03-02 18:18:48
【问题描述】:

我不知何故在 Unity 中得到了一个空引用异常。我为我的武器类创建了一个构造函数,并创建了另一个武器类(继承自 monobehaviour),它在其中创建具有统计数据的武器。在pistol.Stats(10, 0.5f, 2, 5, new Vector2(0.2f, 0.09f)); 中发生了一个空引用。

脚本 1:

public class WeaponClass
{
    public float damage, spread, bulletsPerSec, rotationSpeed;
    public string name;
    public Vector2 shootPoint;
    private Image image;

    public WeaponClass Stats(float Adamage, float Aspread, float AbulletsPerSec, float ArotationSpeed, Vector2 Ashootpoint)
    {
        damage = Adamage;
        spread = Aspread;
        bulletsPerSec = AbulletsPerSec;
        rotationSpeed = ArotationSpeed;
        shootPoint = Ashootpoint;
        return this;
    }
}

脚本 2:

public class Weapons : MonoBehaviour
{
    private PlayerControlls _playerControlls;
    private WeaponClass pistol, m4 = new WeaponClass();
    private Bullet _bullet;
    public WeaponClass currentWeapon;
    private GameObject bullet;
    public Rigidbody2D bulletRb;
    private float randomdirection;
    public float randomdirectionangle;
    
    void Start()
    {
        pistol.Stats(10, 0.5f, 2, 5, new Vector2(0.2f, 0.09f));
        currentWeapon = pistol;
        Debug.Log(currentWeapon);
    }
    
    void Update()
    {
        
    }

    public void Shoot()
    {
        randomdirection = Random.Range(-currentWeapon.spread, currentWeapon.spread);
        randomdirectionangle = Mathf.Atan2(randomdirection, currentWeapon.shootPoint.x) * Mathf.Rad2Deg;
        Quaternion bulletrotation = new Quaternion(0, 0, randomdirectionangle, 0);
        
        GameObject bulletclone = Instantiate(bullet, currentWeapon.shootPoint, _playerControlls.GunEquipped.transform.rotation);
        bulletRb = bulletclone.GetComponent<Rigidbody2D>();
    }
}

【问题讨论】:

  • 你只是构造/实例化了m4

标签: c# unity3d


【解决方案1】:

在一行中声明/初始化多个字段时要小心!

你在做什么

private WeaponClass pistol, m4 = new WeaponClass();

等于写作

private WeaponClass pistol; // NOT INITIALIZED!
private WeaponClass m4 = new WeaponClass();

所以你想要的是

private WeaponClass pistol = new WeaponClass(), m4 = new WeaponClass();

我通常会完全不鼓励使用它,而是总是在单独的行中使用它:

private WeaponClass pistol = new WeaponClass();
private WeaponClass m4 = new WeaponClass();

原来是这样

  • 可读性更好
  • 如您所见,不易出错
  • 更好的可维护性,您可以通过这种方式轻松添加或删除字段

【讨论】:

  • 谢谢!至少我学会了形式错误。
猜你喜欢
  • 1970-01-01
  • 2013-02-17
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 2019-03-13
相关资源
最近更新 更多