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?