-1

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d9c061b1c154f5ae/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53) Gun.Update () (at J:/W.A.R/Assets/Scripts/Gun.cs:16)

thats the error i get and here my code for the gun class

using UnityEngine;
using System.Collections;

public class Gun : MonoBehaviour {

    public GameObject bullet = null;
    public float bulletSpeed = 500f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Mouse0)) {

            /*
             * Instantiate the bullet using the prefab and store it into the shot variable
             */

            GameObject shot = GameObject.Instantiate(bullet, transform.position + (transform.forward * 2), transform.rotation) as GameObject;

            /*
             * Adding force
             */
            shot.rigidbody.AddForce(transform.forward * bulletSpeed);
        }
    }
}
apxcode
  • 7,696
  • 7
  • 30
  • 41
  • It looks like you are trying to instantiate a bullet, however, you set the bullet to null, and in the code provided have not set it to something else. You cannot use a null object. – CC Inc Sep 10 '12 at 12:26
  • GameObject looks like a Base class, so probably you'd like a class Bullet that is of type GameObject, thus setting bullet = new Bullet(). – Amadeus Hein Sep 10 '12 at 12:50
  • @user1526784 Check my answer for an example. – CC Inc Sep 10 '12 at 13:01

1 Answers1

2

The problem is, is that the bullet GameObject is null, and because it has not been set, when he tries to instantiate a null object, it throws an exception.

What you can do depends on the gameobject. You can use GameObject.Find to get the GameObject bullet and then assign that to the bullet var.

public GameObject bullet = GameObject.Find("NameOfTheBulletGameobject");

Another way you can do this is just drag the bullet gameobject onto the variable in the inspector.

public GameObject bullet;

Then, just take the actual bullet object and drag it onto the bullet variable in the script, in the inspector.

Hope it helps!

CC Inc
  • 5,842
  • 3
  • 33
  • 64