Search Unity

Unwanted prefab offset after parenting

Discussion in 'Scripting' started by lordofd555, Jun 18, 2021.

  1. lordofd555

    lordofd555

    Joined:
    May 5, 2020
    Posts:
    2
    For an RPG game I am making a status bar that is displaying pictures according to the buffs and debuffs applied to the character.

    For that I instantiate a prefab, change the texture and parent it to the canvas of the character
    Code (CSharp):
    1. status = Instantiate(statusPrefab);
    2. status.GetComponent<RawImage>().texture = statusTexture;
    3. status.transform.SetParent(target.transform.GetChild(2));
    After that I adjust the position with
    Code (CSharp):
    1. RectTransform rt = status.GetComponent<RectTransform>();
    2. rt.localPosition = new Vector3(0f, 0.225f, 0f);
    However, for some reason the instantiated prefab gets offset by (0.5, 0.1, 0) resulting in an actual position of (0.5, 0.325, 0).
    To find the cause for the offset I tried various different things, but I couldn't find it.
    I tried to counter it by making sure that the pivot and the anchor stayed the same. So, before setting the position I execute this code
    Code (CSharp):
    1. rt.pivot = Vector2.zero;
    2. rt.anchorMin = Vector2.zero;
    3. rt.anchorMax = Vector2.zero;
    4. rt.position = Vector3.zero;
    5. rt.localEulerAngles = Vector3.zero;
    6. rt.localScale = Vector3.one;
    That didn't change a thing and the only way I found to counter the offset is by specifically subtracting it like
    Code (CSharp):
    1. rt.localPosition = new Vector3(0f, 0.225f, 0f) - new Vector3(0.5f, 0.1f, 0f);
    But I am not satisfied with this "solution" as it is really sloppy and random.

    The prefab's components look like this:
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    There's a variant of Instantiate - you can pass in the desired parent as the second parameter, so you don't have to reparent it afterwards. That should do what you want.
     
  3. lordofd555

    lordofd555

    Joined:
    May 5, 2020
    Posts:
    2
    That's neat. I will give it a try right away.
    Edit: Did give me the same behavior. The problem persists. But at least I saved one line of code
     
    Last edited: Jun 18, 2021
  4. Reedex

    Reedex

    Joined:
    Sep 20, 2016
    Posts:
    389
    There is grid layout component also.