Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Destroy an object created with Instantiate()

Discussion in 'Scripting' started by RacerNiel, Dec 21, 2015.

  1. RacerNiel

    RacerNiel

    Joined:
    Dec 21, 2015
    Posts:
    2
    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?
     
  2. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Use GameObject obje;
     
    Kiwasi likes this.
  3. RacerNiel

    RacerNiel

    Joined:
    Dec 21, 2015
    Posts:
    2
    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...)
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.