NullReferenceException

Hi I’m making a 2D platformer with guns.

I’m having trouble with my weapon pickup scripts.
I want to

  1. Give player a new weapon (gameObject).
  2. Destroy the old weapon.
  3. make references for the old weapon point to the instance of the new weapon.

I have a “WeaponPickup” class that hold a reference to the prefab.
I want to pass this to a function on my “PlayerActions” -script.

It looks like this:

public void GiveWeapon(GameObject newWeapon)
    {
        
        Debug.Log(newWeapon);
        GameObject gunClone;
        gunClone = Instantiate(newWeapon, gunAP.position, Quaternion.identity) as GameObject;
        if (!facingRight)
            newWeapon.transform.localScale = new Vector3(-newWeapon.transform.localScale.x, newWeapon.transform.localScale.y, newWeapon.transform.localScale.z);
        gun = newWeapon;
        gun.transform.parent = gunAP;
        gunProperties = gun.GetComponent<GunProperties>();
        gP1 = gun.transform.Find("GP1");
        
    }         

I get this error:
NullReferenceException: Object reference not set to an instance of an object
NewPlayerController.GiveWeapon (UnityEngine.GameObject newWeapon) (at Assets/Scripts/Player/NewPlayerController.cs:389)
WeaponPickup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/WeaponPickup.cs:35)

Essentially I want to replace a child of my PlayerCharacter with a Prefab and have the new prefab “stick to” (become child of) my Player’s Arm-GameObject.

PS the Debug.Log above correctly posts the name of the new Weapon GameObject passed from my “WeaponPickup” class.

If line 4 returns a gun then your problem is not newWeapon.

Your problem is probably gunAP.position. Throw that into a debug statement and see what happens.

Things to check

  • Does gunAP exist?
  • Is gunAP a Transform?
  • Has gunAP been assigned a value?
  • Is gunAP declared in this script?
  • Is gunAP out of scope? Out of scope typically happens when it is declared inside another method. In general variables only exist until the close of the curly brackets they were declared in.
  • Has gunAP been destroyed by some other script?

From what I can see, it appears you are referencing newWeapon when you should be referencing gunClone. On this line:

gun.transform.parent = gunAP;

If gun is newWeapon, since you set it as so:

gun = newWeapon;

Then gun.transform might be null if newWeapon is a prefab that is not actually in your scene.

My guess is this script should be referencing gunClone instead of newWeapon after new weapon has been cloned.