0

I am making a game based on design of super crate box: player collides with box and it chooses a random weapon.
The problem is if the shotgun bullet is active while I shoot again using another gun, I get the exception (I will obviously later make the bullet disappears but the problem also occurs even if the bullet disappears).

I need to press the key really fast for it to happen so I assume the exception only happens when the shotgun bullet is active.

Exception scenario:

  • player picks up shotgun
  • player fire bullet (bullet doesn't disappear for testing purposes)
  • player pick up another gun
  • while bullet is still active, player presses control again to fire bullet => Exception

The line where the exception occurs is the first instance of this Transform cameraTransform = player.transform;.

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;
     }
}
Kardux
  • 2,117
  • 1
  • 18
  • 20
SubZero
  • 1
  • 1
  • 2
    Please provide the full content of the exception log. – zwcloud Mar 27 '17 at 08:38
  • Few advises for your code: instead of calling `Transform cameraTransform = player.transform;` each time the user presses a key, register it at `Start()` and save it into a private variable. Also, instead of `if (bulletInScene != null) { if (t.name.Contains("Bullet1(Clone)")) { //SOMETHING } }`, you can do `if (bulletInScene != null && t.name.Contains("Bullet1(Clone)") { //SOMETHING }`. This way your code will be much more cleaner and easier to read. – Kardux Mar 27 '17 at 09:32
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – FCin Mar 27 '17 at 10:51
  • Ok thanks for advice guys I'll try indent it better. EDIT Thanks for that made it alot easier. – SubZero Mar 27 '17 at 10:52

1 Answers1

0

The error suggest that player is not set. Judging from the code I assume you either have a prefab and you set it in the inspector, or another script is supposed to set it.

Maybe you are using a different prefab for whatever reason when the shotgun bullet is active and you forgot to assign player on that prefab.

Or the script supposed to dynamically assign player in the FireGun MonoBehaviour is still "looking" at the shotgun's bullet's script and not the new gun's.

DailyDoli
  • 39
  • 5
  • Player is set fine, I do have another script, but its just this one I think is problem. This is what error message says NullReferenceException: Object reference not set to an instance of an object FireGun.checkWeaponType () (at Assets/Scripts/FireGun.cs:133) FireGun.Update () (at Assets/Scripts/FireGun.cs:58) – SubZero Mar 27 '17 at 09:06
  • Still attempting to fix it using the normal bullet for the shotgun works fine just not the new bullet no idea why. – SubZero Mar 27 '17 at 09:47
  • Hey guys so I completly modified it not using the foreach loop I found a better solution but still want to know why it didn't work. But I have a question in programming in general if you can't figure out a problem after say 7 hours like today, do you think its ok to try a new solution or should you learn why it doesn't work? – SubZero Mar 27 '17 at 12:05
  • It is always difficult to guess when you should give up on a solution. If I spend "too much" (nothing accurate) time on a problem I tend to try something different simply because even on something simple, being too focused on it can stuck my reasoning. I feel like it's a good idea if you can to keep the code (commented for example) and try to come back to it later with your mind cleared and/or more knowledge, then maybe you have more chance to understand why it didn't work. – DailyDoli Mar 27 '17 at 12:11
  • Guys I fixed it with this code! I changed this line if (t.name.Contains ("Bullet1(Clone)")) to if (t.name.Equals("Bullet1(Clone)")) Now works but no idea why? Contains is case sensitive so the 2 bullets can be seen as different names I don't see how they conflict anyone have any ideas? – SubZero Mar 28 '17 at 02:02
  • Sorry for the next comment can't edit above one but HOLY SHIT is this line why? transform.Find("Bullet1(Clone)").transform.parent = null; the "Find" method looks for the EXACT name but we can't find it? – SubZero Mar 28 '17 at 02:11