- Home /
Getting an error message when destroying a instantiated prefab
I've been taking the create with code course and I am stuck on 7th step on lesson 2.2. Here is a link to the lesson I'm taking.
Carl instructs us to create a new script and attach it to the projectile with this code written inside.
public class DestroyOutOfBounds : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.z > 50) {
Destroy(gameObject);
}
}
}
Now what it's supposed to do is destroy the projectile after it instantiates and goes out 50 units on the Z-Axis. However, when I test it out, the spacebar becomes irresponsive and I get an error message down below that says
"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. PlayerController.Update () (at Assets/Scripts/PlayerController.cs:37)"
Has Unity's code changed since Carl did this video? because I can't for the life of me figure out why it's doing this, it feels like the Unity Engine is ignoring the conditions of the if statement and destroying it immediately!
Is this script on the original prefab as well? (The object you are instantiating from). Is so, that will be destroyed and therefore you can't instantiate from it anymore, since it doesn't exist, and so you'll get an error when trying to instantiate it next time, in the PlayerController script. @HellGateWizard
Could you share the code which instantiates the Prefab?
Once you make the projectile as Prefab, make sure that no more projectile object resting in your hierarchy. Delete it or Deactivate it or $$anonymous$$ake sure you referenced the "Prefab projectile asset " on your gun instead of the object that is in the hierarchy
Look at your PlayerController script at line 37. What did you put there, or can you show us the code?
Can you post PlayerController? this is where the error comes from. also, the error is pretty clear, and you probably have to add a null check.
Answer by Revolution_Game · Jan 02, 2021 at 02:09 PM
I think you instantiate your object at > 50 in z-axis, so it gets destroyed once instantiated.
That wouldn't necessarily create an error message. The desired effect is to destroy the clone in the first place. Unless, another script is trying to access anything from the clone.
Your answer
![](https://koobas.hobune.stream/wayback/20220613022503im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Scripts not on instantiated GameObjects? 1 Answer
Firing only a single projectile at a time, then adding a second. 2 Answers
i want to destroy a projectile after it passes a limit on x axis after instantiation(2d game) 1 Answer
walk through an object once 0 Answers
Destroying childs and Instantiate [C#] 0 Answers