Alright so I’m working on making my first FPS, first as in I started 2 days ago. I’m just working on coding mostly. And I’ve run into this problem:
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.
Shooting.Update () (at Assets/Scripts/Shooting.cs:29)
Here are my scripts
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour {
public GameObject zero;
public GameObject one;
float bulletImpulse = 20f;
public GameObject firePos;
float ranNum = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Debug.Log (ranNum);
if( Input.GetButton("Fire1") ) {
ranNum = Random.Range (-1.0f, 1.0f);
if (ranNum >=0 && ranNum <=1)
{
GameObject bullet2 = (GameObject)Instantiate(zero, firePos.transform.position + firePos.transform.forward, firePos.transform.rotation);
bullet2.rigidbody.AddForce( firePos.transform.forward * bulletImpulse, ForceMode.Impulse);
}
else
{
GameObject bullet1 = (GameObject)Instantiate(one, firePos.transform.position + firePos.transform.forward, firePos.transform.rotation);
bullet1.rigidbody.AddForce( firePos.transform.forward * bulletImpulse, ForceMode.Impulse);
}
}
}
}
And
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
public static bool hit = false;
float lifeTime = 6f;
float hitTime = 1f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
lifeTime -= Time.deltaTime;
if (lifeTime <= 0)
Dead ();
if (hit) {
hitTime --;
if (hitTime <= 0) {
hit = false;
hitTime = 1f;
}
}
}
bool OnCollisionEnter (Collision collision){
if (collision.gameObject.tag == "Enemy") {
hit = true;
} else
Destroy(gameObject);
return hit;
}
void Dead(){
Destroy (gameObject);
}
}
I’m trying to figure out why, when the bullets first start to be destroyed because of the lifeTime running out, they stop shooting. I’m using 2 prefabs for the 2 different bullets that shoot. Both of them give this error. Any ideas?
Thanks for your time.
Edit
It seems that, no matter what, when the Destory(gameObject); is called, Unity can no longer use the prefab. Anyone have any idea why that may be?