Dracolyte
Dracolyte

Reputation: 11

Unity null exception when Instantiating class

I somehow get a null reference exception in Unity. I made a constructor for my weapon class and made another weapon class (which inherits from monobehaviour), where it creates the weapons with its stats. in pistol.Stats(10, 0.5f, 2, 5, new Vector2(0.2f, 0.09f)); happens a null reference.

Script 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;
    }
}

Script 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>();
    }
}

Upvotes: 1

Views: 302

Answers (1)

derHugo
derHugo

Reputation: 90620

Careful when declaring/initializing multiple fields in a single line!

What you do in

private WeaponClass pistol, m4 = new WeaponClass();

equals writing

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

So what you want would be

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

I would in general discourage from using this at all and rather always do it in separate lines:

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

as this is

  • better readable
  • as you see less error prone
  • better maintainable, you can easily add or remove fields this way

Upvotes: 1

Related Questions