Hello, in my current 2d game project some UI images need to be added from code (since their max number should be editable). After I instantiate them 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 them
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);
}
}
Whether you’re making a 2D game or not, the UI forum is here where you’ll get quicker help on these UI related issues.
Made a post there as well. 2d is because I did use similar setup in 3d and there werent any visibility problems (havent checked if there was any Z negative offset though)
There is no 2D/3D, it’s the same system so not sure what you mean here.
Orthographic camera. I need to change its Size at one moment of the game. This makes UI elements with negative Z positions to disappear.
Fixed thanks to response from UI thread: Problem with adding UI elements from code
1 Like