Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Set Parent like drag a prefab in the hierachy

Discussion in 'Scripting' started by ZeraTFK, Jun 8, 2015.

  1. ZeraTFK

    ZeraTFK

    Joined:
    Sep 13, 2014
    Posts:
    15
    Hi,

    im i kind of confuse..
    i have a charakter. and a prefab of a hat with the right position, rotation and scale.
    now i put the hut as prefab in the project view.

    if a drag and drop the prefab from the project view on my charakter in the hierachy.. the pos,scal, rot is ok.

    now i try to add the hat with a c# script, but the pos, scale and rot are not ok

    Code (CSharp):
    1. Transform[] allChildren = CharGA.GetComponentsInChildren<Transform>();
    2.             foreach (Transform child in allChildren) {
    3.                 if(child.name == "BigHeads HeadNub")
    4.                 {
    5.                     GameObject tmpGA = CResourceManager.LoadGameObjectFromName(tmpitem.ga_Name);
    6.                     tmpGA.transform.SetParent(child);
    7.                     break;
    8.                 }
    9.             }
    how can i simulate the drag and drop from the project view on the character in the hierachy?
    there is something diffent.
     
  2. NeilM0

    NeilM0

    Joined:
    Mar 31, 2009
    Posts:
    135
    Chances are you will want to add the line:
    Code (CSharp):
    1. tmpGA.transform.localPosition = Vector3.zero;
    immediately after you set the parent.

    If you have an offset in the prefab that you would like to have, you're going to have to do this:

    Code (CSharp):
    1. Vector3 backupOffset = tmpGA.transform.localPosition
    2. tmpGA.transform.SetParent(child);
    3. tmpGA.transform.localPosition = backupOffset;
    Setting the parent doesn't move the object in world space. So if the parent isn't at [0,0,0], it won't move to where you want it. Once the object is parented, if you set the offset to [0,0,0] in the local position, it will snap to the parents pivot point.
     
    ZeraTFK likes this.
  3. ZeraTFK

    ZeraTFK

    Joined:
    Sep 13, 2014
    Posts:
    15
    Ok, i already tryed this but with the wrong result.

    with this script it looks: (wrong)


    and if i drag and drop it from project view to the bone of my character in the hieracy it works right:

     
  4. NeilM0

    NeilM0

    Joined:
    Mar 31, 2009
    Posts:
    135
    Try backing up the .localRotation and .localScale in the same way that .localPosition was, and then set them after it has been parented.