Search Unity

Parenting objects

Discussion in 'Scripting' started by chhenderson, Feb 22, 2010.

  1. chhenderson

    chhenderson

    Joined:
    Feb 15, 2010
    Posts:
    10
    So I posted a thread last week about picking up and dropping an object. And it works just fine, but I'm wondering if I could make it simpler.

    I'm thinking all I need to do is parent the object on the ground to the player when he comes in contact with it, so that it attaches to his body and follows him around.
     
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    Can you post the script, or else a link to your previous thread if the code is already there?
     
  3. Apache

    Apache

    Joined:
    Sep 26, 2008
    Posts:
    134
    You can make parents simply by using this piece of code:
    Code (csharp):
    1.  
    2. GameObject child, father;
    3.  
    4. child.transform.parent = father.transform;
    Hope it can help !!! ;)
     
  4. trinitysj

    trinitysj

    Joined:
    Jan 15, 2010
    Posts:
    54
    I would really like to use this. I have a horizontal platform and when i stand on it it moves underneath me and i fall off. it moves over water so i dont want to fall in. how do i stick my game object to the platform so that it moves with the platform until i walk off of it?

    thanks
     
  5. Apache

    Apache

    Joined:
    Sep 26, 2008
    Posts:
    134
    Well, first of all if you want to stay on that platform withouth moving anymore the player, you need to disable the input catcher and then use this kind of code:
    Code (csharp):
    1. player.transform.parent = platform.transform
    where player and platform are 2 gameobjects or 2 generic components (if you prefer you can directly pass the 2 trasforms references).
    Instead, if you want to move on the platform but don't want to fall off it, you can make a jail with box colliders all around the platform so that the player cannot fall off. Obviously the jail must be child of the platform and can be enabled or disabled when you prefer via script.

    Let me know if I was enough clear !! :)