Destroy an object created with Instantiate()

i have been trying to destroy the exact object that i created with Instantiate().

but i keep getting various errors

here is what i currently have:

Object obje;
obje = Instantiate (obtype, transform.position, Quaternion.identity);
Destroy(obje);

the error in this code is that i “can’t destroy tranform component. call destroy on the game object.”

so, how do i call destroy on the game object if i have the transform?

when i search i see that i should be able to type

Destroy(obje.GameObject);

but that doesn’t work either.

can someone please tell how to destroy the exact item that created or point me in the right direction?

Use GameObject obje;

1 Like

Thank Hippocoder

you got me on the right track but this is what i think i needed to do:

private Transform obje;
obje = Instantiate (obtype, transform.position, Quaternion.identity) as Transform;.
Destroy(obje.gameObject);

(for some reason GameObject didnt give any errors but the instantiated object did not disappear either…)

That’s because you used safe casting with as. Using as should always be followed by a null check. You should have seen a runtime error saying the object you are trying to destroy is null.

Better to use the generic version of instantiate or use explicit casting.