Reputation: 384
How do I instantiate multiple instances of the FloatingText that destroys itself in 1 second?
I'm using this script to instantiate a floating text.
if (Input.GetKey("w")) {
GameObject floatingText = Instantiate(floatingTextPrefab, position, Quaternion.identity, transform);
}
In the FloatingTextPrefab, I added a component script called DestroyTimer. So tht text disappears in 1 second.
void Start()
{
Destroy(gameObject, 1f);
}
Now whenever I press the key, it says
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Why is it deleting the prefab, instead of itself as an instance?
I'm trying to follow this but he doesn't encounter the same problem.
https://youtu.be/LjNsDVYXfrk?t=364
Upvotes: 0
Views: 1484
Reputation: 142
If your prefab is also in the 3D scene, it will execute the destroy itself whenever it's visible.
It means that your prefab already destroy itself before you pressing "W".
Below is the suggested way to do it.
if (Input.GetKey("w"))
{
GameObject floatingText = Instantiate(floatingTextPrefab, position, Quaternion.identity, transform);
Destroy(floatingText, 1f);
}
and please remove the destroy function within your prefab:
void Start()
{
//Destroy(gameObject, 1f);
}
Edit:
If you want to use your original setup. Two options:
option 1: saving it as prefab, and assign the prefab from asset folder.
option 2: always disabling the prefab by default, only enabling the instantiated object.
Upvotes: 2
Reputation: 384
I think I figured it out. I need to delete the FloatingTextPrefab in the scene, only leave it in the assets. And in the components menu associate the one from Assets instead of the one in the scene.
Upvotes: 0