Search Unity

making an object child of annother

Discussion in 'Scripting' started by abysswolf, Sep 27, 2014.

  1. abysswolf

    abysswolf

    Joined:
    Oct 15, 2012
    Posts:
    62
    Hi guys its me again with a silly question, i thank in advance to all of you who have helped me to this point, im just making the final touches to my demo ! but, to solve a bug i need one thing

    to make an object to become child of annother via script, that is :

    step 1 : Object A detects that Object B is on the scene
    step 2 : Objects A makes itself parent of Object B

    thanks in advance !

    i have a solution here but is written in Js...


    Code (JavaScript):
    1. var objPrefab: GameObject; // new object prefab
    2.     ...
    3.     var newObject: GameObject = Instantiate(objPrefab, ...); // create the new object
    4.     transform.parent = newObject.transform; // newObject is this object's new daddy!
    5.     ...
     
    Last edited: Sep 27, 2014
  2. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    in C# the actual parenting part would be exactly the same, what's your issue? you don't know how to instantiate in C#?

    the script above in C# would be

    public GameObject objPrefab

    ...

    GameObject newObject = (GameObject)Instantiate (objPrefab, ...) as GameObject;
    transform.parent = newObject.transform
     
  3. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    or if you're using unity 4.6 you can do transform.SetParent (newObject.transform);
     
  4. abysswolf

    abysswolf

    Joined:
    Oct 15, 2012
    Posts:
    62
    thanks ! i successfully modded the script to my needs thanks to that... :)