Quick question about Instantiating Destroying (C#)

Hi Everyone!

I’ve more or less run into a wall (could be im tired, or could be i just cant figure it out :smile: one of those two will do), with the instantiating and destroying of objects in my C# code.

I’ve got a:

public GameObject projectile;

with a:

projectile = (GameObject)Instantiate(projectile, transform.position,transform.rotation);

following it a bit later in the code, and it works well (dragged prefab into the transform slot on the object with the script).

The object is spawned, does what i instructed it to and destroys itself - just the way i wanted it to.
However the second time i need it, it fails.

I’ve pretty much localized the problem.
At first i used the Destroy(gameObject, float value) command on the new object to destroy it. This basically deleted the prefab from the instantiater script located on the old object. Which lead the 2nd attempt to complain about null references.

Then i tried changing it to “Destory(this, float value)” - which diddent delete the original prefab, but instead renamed it to (event after the original is dead) …which again made my instantiater complain.
However the prefab i dragged into the “public GameObject projectile” part in the editor, renames itself to “(clone)” - which then makes my instantiating line vomit and die by giving me a:
“NullReferenceException: Object reference not set to an instance of an object” error - pointing to the instantiating line.

As the code is only 2 lines - i’ll include it here:
Full instantiating code:

projectile = (GameObject)Instantiate(projectile, transform.position,transform.rotation);
MagicFlyScript myFly = projectile.GetComponent(typeof(MagicFlyScript)) as MagicFlyScript;

Basically the code i have for shooting makes is so that the user cannot instantiate a 2nd projectile at any time. Only 1 can ever exist at a time, which is why i wouldent mind that clone thing to go away :slight_smile:

Any tips on how i can get my projectile code up and running, with a destroyer - so that it only destroys the object and not the prefab (and dosent rename the prefab so its unuseable teh seoncd time around!)?

Hopefully my text isent too rambling and incoherent, i’ve been messing with alot of code today so my mind has just gone completely blank.

Thanks in advance!

Your problem is very simple if you step back and think about it.

You have a variable that contains a reference to a prefab. You use that reference to create an object and assign it to the variable that was containing the prefab. Your variable is now an object in your scene (which you then delete) and not a prefab since you overwrote it.

Use a second variable and you’ll avoid this problem.

Thanks a bunch @Sycle :slight_smile: that was it.