Problem with adding UI elements from code

Hello, in my current 2d game project I add some UI sprites from code (since their max number should be editable). After I instantiate and parent them to Canvas object, they gain unexpected negative Z-axis offset which messes up with their visibility in some situations. I’ve already tried everything (like zeroing out Z component of Transform.position and RectTransform position, or copying the position from the object already attached to the canvas), but I cannot get rid of this negative value in Z. Strangely enough, it is editable in Scene mode, but not by code
The code part that adds images

        if (DashIcon != null){//prefab originally attached to the canvas; then copied with Instantiate
            Dash_T = DashIcon.GetComponent<RectTransform>();
            dashIcons.Add(DashIcon);//added to the same list as cloned instances
            float IconStep = (Dash_T.rect.width + 0.1f*Dash_T.rect.width)*DashIcon.transform.localScale.x;
            float _IconStep = 0f;
            for (int i = 0; i <= MaxDashes; i++){
            _IconStep += IconStep;
            GameObject icon = (GameObject)Instantiate(DashIcon,Vector3.zero,Quaternion.identity);
            icon.GetComponent<RectTransform>().SetParent(canvas.transform);
            icon.transform.localScale = DashIcon.transform.localScale;
            //setting position both of Transform or RectTransform gave the same wrong result
            //icon.GetComponent<RectTransform>().position = new Vector3(DashIcon.GetComponent<RectTransform>().position.x,DashIcon.GetComponent<RectTransform>().position.y,0f);
            icon.GetComponent<RectTransform>().anchoredPosition = Dash_T.anchoredPosition + new Vector2(Dash_T.anchoredPosition.x + _IconStep,0f);
            dashIcons.Add(icon);
            }
        }

you should either pass false as second parameter of SetParent or (better) use the Instantiate-overload where you directly pass the parent. If you do the latter, it is also better for performance because the UI have to be resorted one time instead of two times internally.

1 Like

Setting worldPositionStays of SetParent to false indeed fixed the z position appearing from nowhere. And as a consequence- got rid of display problems