Search Unity

Destroy object help

Discussion in 'Getting Started' started by skeleton-king, Mar 19, 2015.

  1. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    I have a gameobject called item which has script attached to it if (Input.GetMouseButtonUp(0)) Destroy(this.gameObject);
    My Gameobject has several child objects. I want to destroy the child object which gets clicked. But the above code destroys parent object as well as the child object. Anyway to only destroy child object??
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    If your child object is being referenced by name:
    Code (CSharp):
    1. if (Input.GetMouseButtonUp(0)) {
    2.   GameObject.Destroy(transform.find("ChildObjectYouWantToKill"));
    3. }
     
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,448
  4. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Derp. @mgear's response is more accurate. I was posting while distracted (PWD) and didn't read the question properly.
     
  5. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    problem is i got lots of objects so putting script on everyobject is kinda tedious.
    Is there any way it will work with putting only 1 script.
    Objects are same just sprites are different, but there are lots of objects in it.
     
  6. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    How are those objects generated? If they are instances of prefabs then you can simply add the script to the prefabs. o:
     
  7. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    I did this but it seems to destroy all objects in scene with script attached when i click on one object.
    How to destroy the only object that you click on t.
     
  8. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Are you sure you're searching through the object hierarchy of the object you clicked on, then?

    Posting your code is a good way to get specific help, by the way.