- Home /
MissingReferenceException after destroying a prefab?
I'm sure this gets asked all the time but I can't seem to find an answer that works. So, brand new to Unity and gave development in general.
I've created a generic GameObject to act as a spawn point when the user left clicks for a projectile prefab that gets destroyed after 5 seconds. This works, except after 5 seconds if I try to fire to again I get a MissingReferenceException saying The object of type 'GameObject' has been destroyed but you are still trying to access it.
Somehow, it's removing that same projectile prefab from my GameObject that spawns them.
Recap: -"Empty" GameObject with a script attached that spawns a Projectile prefab on mouse up -Prefab has a script attached that destroys a designated gameObject -After the prefab is destroyed, my mouse up no longer works and throws a MissingeReferenceException
Script #1 (attached to part of the player's model):
var power: float = 1000;
var bulletPrefab: GameObject;
function Update () {
if (Input.GetMouseButtonUp(0)){
var pos: Vector3 = transform.position;
bulletPrefab = Instantiate(bulletPrefab, transform.position, transform.rotation);
bulletPrefab.rigidbody.AddForce(Vector3.forward * power);
audio.Play();
}
}
Script #2 (attached to prefab):
var ttl = 5;
var thingToDestroy: GameObject;
function Awake() {
Destroy(thingToDestroy,ttl);
}
In both scripts, the GameObject variable is the same prefab and I can only assume this is my problem... But I have no idea what I should be doing?
Also, in script #2, if I try simply Destroy(this, ttl) it doesn't destroy the object the script is attached to?
Answer by Bunny83 · Aug 07, 2013 at 02:24 AM
Well, your bulletPrefab variable used to hold a reference to a prefab. When you instantiate the prefab you get a prefab instance but you overwrite your bulletPrefab variable with the reference to the instance, so the reference to the prefab is lost. When the one instance you have created gets destroyed, bulletPrefab will become null.
You should use a local temp-variable like this:
var power: float = 1000;
var bulletPrefab: GameObject;
function Update () {
if (Input.GetMouseButtonUp(0)){
var clone : GameObject = Instantiate(bulletPrefab, transform.position, transform.rotation);
clone.rigidbody.AddForce(Vector3.forward * power);
audio.Play();
}
}
Good catch, I didn't see the bit about using the same variable.
Answer by Eric5h5 · Aug 07, 2013 at 01:56 AM
Don't bother with script #2, just do
Destroy (bulletPrefab, timeToLive);
in script #1.
I had thought of that, but I'm getting the same issue :(
Are you actually using prefabs? Objects in the scene are instances, not prefabs.