Search Unity

Unity 3d Parenting with Code?

Discussion in 'Scripting' started by ohLogical, Mar 10, 2012.

  1. ohLogical

    ohLogical

    Joined:
    Feb 12, 2012
    Posts:
    98
    I need to make an object I Instantiate become the child of another object in my scene when it spawns. I've used google, I can't find anything.

    Ideas?
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
  3. ohLogical

    ohLogical

    Joined:
    Feb 12, 2012
    Posts:
    98
    That doesnt work for me. Can someone please just write it out for me?
     
  4. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Code (csharp):
    1.  
    2. // Makes the camera follow this object by
    3. // making it a child of this transform.
    4.  
    5. // Get the transform of the camera
    6. var cameraTransform = Camera.main.transform;    
    7.  
    8. // make it a child of the current object
    9. cameraTransform.parent = transform;
    10.  
    11. // place it behind the current object
    12. cameraTransform.localPosition = -Vector3.forward * 5;
    13.  
    14. // make it point towards the object
    15. cameraTransform.LookAt(transform);
    16.  
    Another example:
    Code (csharp):
    1.  
    2. // Detaches the transform from its parent.
    3. transform.parent = null;
    4.  
     
  5. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    How is the documentation not exactly that?!
     
  6. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    969
    Something like this?

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var prefab : Transform;
    5. var parentObject : Transform;
    6.  
    7. function Start ()
    8. {
    9.     var anObject = Instantiate(prefab, Vector3.zero, Quaternion.identity) as Transform;
    10.     anObject.parent = parentObject;
    11. }
    12.