Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantiate object based on local position of another object without parenting?

Discussion in 'Scripting' started by derkoi, Jan 2, 2014.

  1. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    I'm trying to Instantiate an object based on the local position rotation of another object without parenting.

    I made a crappy diagram to show what I mean.

    $position.jpg

    Can anyone help please?

    Thanks
     
    Last edited: Jan 2, 2014
  2. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
  3. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255

    It's not the instantiating part that I'm having issues with, it's the positioning, I've tried...

    Code (csharp):
    1.     public GameObject targetObject;
    2.  
    3.     public Vector3 offset;
    4.  
    5.    
    6.     void Start () {
    7.         transform.rotation = targetObject.transform.rotation;
    8.         transform.position = targetObject.transform.localPosition + offset;
    9.     }
    10.  
    and a bunch of different combinations of the above.
     
    Last edited: Jan 2, 2014
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Why localPosition and not position? Is the target parented to something? Should the offset be dependent of the target's orientation?
     
  5. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    I've tried position too, I've tried positioning at the target object position, then rotation to match the target objects rotation then offsetting but it ends up moving in world space.
     
  6. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    Should I just instantiate objects, parent them to the target object, position them relative to the target then unparent them?

    Sounds a bit dodgy.
     
  7. gfoot

    gfoot

    Joined:
    Jan 5, 2011
    Posts:
    550
    You can convert a position relative to a transform into world space using transform.TransformPoint.
     
  8. derkoi

    derkoi

    Joined:
    Jul 3, 2012
    Posts:
    2,255
    Thanks, that did the trick:

    Code (csharp):
    1.     public GameObject targetObject;
    2.  
    3.     public Vector3 offset;
    4.    
    5.     void Start () {
    6.  
    7.         transform.rotation = targetObject.transform.rotation;
    8.         transform.position = targetObject.transform.position;
    9.         transform.position += transform.TransformPoint(offset);
    10.  
    11.     }