Null Reference Exception can’t figure it out

Updated on March 28, 2017 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
7 on March 27, 2017

Hey guys so I am trying to get my shotgun to fire but it seems impossible. Like it fires but then an exception pops up. I can catch it but don’t think that’s the proper way to solve it. Anyways my rpg and smg gun these shoot in similar fashion just different speed with shotgun I want to change it so a object pops up for a quick second around 0.3f then disappears. That works fine aswell. What doesn’t work fine is though if I shoot with the shotgun keep pressing the button or basically the bullet is still active in the scene and if I go pick up another gun and shoot it I get a null reference exception, no idea why.

In a summary:

This game is based on design of super crate box, player collides with box it chooses a random weapon. If the Shotgun bullet is active while I am holding another gun and shooting that gun I get the exception. I will obviously later make the bullet disappears but the problem is even if the bullet disappears it still happends! But I need to press the key really fast for it to happen, still I need to get rid of this. Since I need to press the key really fast I assume the exception ONLY happends when the shotgun bullet is active.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class FireGun : MonoBehaviour
{
//used to hold the guns user is currently holding
public List Guns = new List();
//to acceess pickupbx
public PickupBx pbx;
//holds the current name weapon user is holding
private string weaponFireType;
//this will get the bullet prefab
public GameObject BulletPrefab;
public GameObject shotGunBulletPrefab;
//bullet position on player
public GameObject bulletPosition;
public GameObject shotgunBulletPosition;
//the player
public GameObject player;
//this is the bullet that will be instantiated in scene (rpg/machine gun)
public GameObject bulletInScene;
//this is for the shotgun bullet that will be instantiated
public GameObject ShotgunBulletInScene;
//used to make shooty shoot once every few seconds
private bool shootShottyOnce = false;
void Start()
{
pbx = GetComponent();
}
// Update is called once per frame
void Update()
{
if (GetComponent().flipX == true)
{
bulletPosition.transform.position = new Vector2(-92, 0);
}
else if (GetComponent().flipX == false)
{
bulletPosition.transform.position = new Vector2(92, 0);
}
AddObjectToList(pbx.guns, Guns);
checkWeaponType();
}
//this method will loop through the gameobjects in pbxguns list (first parameter is the guns list in the pickupBx script), (myList is the list in this script)_
void AddObjectToList(List pbxGunsList, List myList)
{
//loop through all gaeobjects in the pbxGunsList list
foreach (GameObject go in pbxGunsList)
{
//if this list in this script doesn't contain the gameObjects from the other script
if (!myList.Contains(go))
{
//clear the list to make sure we don't get duplicates and have weapons in one 1 element
myList.Clear();
//add the gun to our list
myList.Add(go);
}
}
}
//check weapon the player is holding
void checkWeaponType()
{
//loop through the guns and set the string to weapon player is currently holding
for (int i = 0; i < Guns.Count; i++)
{
if (Guns[i].name == "weapons_0(Clone)")
{
weaponFireType = "MachineGun";
}
else if (Guns[i].name == "weapons_1(Clone)")
{
weaponFireType = "Shotgun";
}
else if (Guns[i].name == "weapons_2(Clone)")
{
weaponFireType = "RPG";
}
}
//check if user pressed key and check that guns is not empty ( reason shotgun is inputed here is because the shotgun will shoot differently to the other guns
if (Input.GetKeyDown(KeyCode.LeftControl) && Guns.Count != 0 && weaponFireType != "Shotgun")
{
//make a new gameObject which will hold the bullet in the scene it will instantiate a bullet at the position of the bulletPosition empty gameObject.
bulletInScene = (GameObject)Instantiate(BulletPrefab, bulletPosition.transform.position, Quaternion.identity);
//the transform of the player
Transform cameraTransform = player.transform;
//Makes the player the parent of the GameObject currentGun
bulletInScene.transform.SetParent(cameraTransform, false);
}
if (Input.GetKeyDown(KeyCode.LeftControl) && weaponFireType == "Shotgun")
{
ShotgunBulletInScene = (GameObject)Instantiate(shotGunBulletPrefab, shotgunBulletPosition.transform.position, Quaternion.identity);
//the transform of the player
Transform cameraTransform = player.transform;
//Makes the player the parent of the GameObject currentGun
ShotgunBulletInScene.transform.SetParent(cameraTransform, false);
}
foreach (Transform t in transform)
{
if (bulletInScene != null)
{
if (t.name.Contains("Bullet1(Clone)"))
{
transform.Find("Bullet1(Clone)").transform.parent = null;
if (GetComponent().flipX == true && weaponFireType == "MachineGun")
bulletInScene.GetComponent().AddForce(Vector2.left * 7500);
if (GetComponent().flipX == false && weaponFireType == "MachineGun")
bulletInScene.GetComponent().AddForce(Vector2.right * 7500);
if (GetComponent().flipX == true && weaponFireType == "RPG")
bulletInScene.GetComponent().AddForce(Vector2.left * 4500);
if (GetComponent().flipX == false && weaponFireType == "RPG")
bulletInScene.GetComponent().AddForce(Vector2.right * 4500);
}
}
}
foreach (Transform t in transform)
{
if(ShotgunBulletInScene != null)
{
if (t.name.Contains("ShotgunBullet1(Clone)"))
{
Debug.Log("shotty test");
if (shootShottyOnce == false)
{
StartCoroutine(DestroyShottyBullet());
}
}
}
}
}
IEnumerator DestroyShottyBullet()
{
shootShottyOnce = true;
yield return new WaitForSeconds(0.5f);
Destroy(ShotgunBulletInScene);
shootShottyOnce = false;
}
}
  • Liked by
Reply
1 on March 27, 2017

Line 197 is where I get the exception.

Devoted
on March 27, 2017

197? Does it even exist?

Show more replies
  • Liked by
Reply
Cancel
3 on March 27, 2017

I didn’t even read the code, so I am not going to answer the question. But I will give you a few tips on solving null reference exceptions (it made me go nuts when I got it before I knew those things):

Keep in mind that if you don’t what a reference type is, you should look it up. I won’t explain it here, but I will talk about it.

Look at the line it tells you the exception was thrown at. Look at every object of a reference type you have there. Does it have a .something after it? If so, it can be null, which will cause the exception. So just do something like “Debug.Log(obj == null)”. If it’s false, this is not the problem. Do that one by one until you finish all of the reference types there are and they all return false…you haven’t tested it correctly. There always is at least one that will return true.

Anyways, when you find that one, go back in your code and see what you have done with it. So if it’s a field in the inspector you need to reference, go to the definition and see if you have referenced it. If it’s a parameter of a method, see where you called the method and check the value of the argument you passed to it. Then keep on going and see when it changes to null. Do that to all of the things that can make it null until you find where it became null.

When you find it, just find some way to make it not be null.

Wise
on March 27, 2017

Ok thanks

Wise
on March 27, 2017

Well I didn’t figure it out but I got a new solution. The debug.log didn’t help much, though if I do get the exception and continue the game but delete the shotgun bullet and fire the other gun the exception doesn’t pop up. I thought maybe a collision problem?

Wise
on March 28, 2017

Hey man I figured out the problem it was a name conflict but I don’t get how? Like one is called Bullet1(Clone) and the other is ShotgunBullet1(Clone)

I changed this line if(t.name.Contains(“Bullet1(Clone)”)) to if (t.name.Equals(“Bullet1(Clone)”))

Show more replies
  • Liked by
Reply
Cancel
0 on March 28, 2017

Hey sorry back again doing more testing and realized something this error shouldn’t even be happening because the user presses ctrl and the bullet gets attached to the player then where the error happens it detaches it. How does it not exist if it just deatached it?

I shortened the code this is only part need to focus on:

        //check if user pressed key and check that guns is not empty ( reason shotgun is inputed here is because the shotgun will shoot differently to the other guns
        if (Input.GetKeyDown(KeyCode.LeftControl) && Guns.Count != 0 && weaponFireType != "Shotgun")
        {
            Debug.Log("check for null");
            //make a new gameObject which will hold the bullet in the scene it will instantiate a bullet at the position of the bulletPosition empty gameObject.
            bulletInScene = (GameObject)Instantiate(BulletPrefab, bulletPosition.transform.position, Quaternion.identity);
            //the transform of the player
            Transform cameraTransform = player.transform;
            //Makes the player the parent of the GameObject currentGun
            bulletInScene.transform.SetParent(cameraTransform, false);
        }
        if (Input.GetKeyDown(KeyCode.LeftControl) && weaponFireType == "Shotgun")
        {
            Debug.Log("check for second null");
            ShotgunBulletInScene = (GameObject)Instantiate(shotGunBulletPrefab, shotgunBulletPosition.transform.position, Quaternion.identity);
            //the transform of the player
            Transform cameraTransform = player.transform;
            //Makes the player the parent of the GameObject currentGun
            ShotgunBulletInScene.transform.SetParent(cameraTransform, false);
        }
        foreach (Transform t in transform)
        {
            if (bulletInScene != null)
            {
                if (t.name.Contains("Bullet1(Clone)"))
                {
                    transform.Find("Bullet1(Clone)").transform.parent = null;
                    if (GetComponent<SpriteRenderer>().flipX == true && weaponFireType == "MachineGun")
                        bulletInScene.GetComponent<Rigidbody2D>().AddForce(Vector2.left * 7500);
                    if (GetComponent<SpriteRenderer>().flipX == false && weaponFireType == "MachineGun")
                        bulletInScene.GetComponent<Rigidbody2D>().AddForce(Vector2.right * 7500);
                    if (GetComponent<SpriteRenderer>().flipX == true && weaponFireType == "RPG")
                        bulletInScene.GetComponent<Rigidbody2D>().AddForce(Vector2.left * 4500);
                    if (GetComponent<SpriteRenderer>().flipX == false && weaponFireType == "RPG")
                        bulletInScene.GetComponent<Rigidbody2D>().AddForce(Vector2.right * 4500);
                }
            }
        }
        foreach (Transform t in transform)
        {
            if (ShotgunBulletInScene != null)
            {
                if (t.name.Contains("ShotgunBullet1(Clone)"))
                {
                    Debug.Log("shotty test");
                    if (shootShottyOnce == false)
                    {
                        StartCoroutine(DestroyShottyBullet());
                    }
                }
            }
        }

  • Liked by
Reply
Cancel