- Home /
(4.6 UI) Canvas position resetting itself to (0,0,0) when instantiating a new prefab with the canvas as child?
I have a unit prefab which has a canvas as a child. The canvas contains an image used as a health bar. The position of the canvas on the prefab is something like (0, 2.8, 0), and stays in position for units that I played in the scene BEFORE runtime, yet when I instantiate a new unit from the exact same prefab, the canvas is at (0,0,0). Why?
Nope! In fact, the only canvuses in the scene are the health bar canvuses (canvi?) for the two units
I am also having this issue, for some reason when you instantiate an object with a Canvas in world space it appears to reset the y value of it. I'm working on just having a script get the Canvas component and then re-position it after it's created, but if anyone comes up with an actual fix that'd be great.
While that would work, it doesnt change the fact that there is something else causing that to happen. Whether it be a bug since 4.6 is still in beta, or I'm doing something wrong, I'd like to know what the problem is and/or how to fix it! Otherwise I'll be scared something else will go wrong
Answer by GluedBrain · Sep 01, 2014 at 06:41 AM
You got to set the slider anchors around the health bar slider, assuming you've used slider for your health bar. Setting the anchors in a correct manner will help you get rid of this issue.
shows you how to create a Health bar using slider and set the anchor points of the slider. Hope this help!!
I didn't use a slider :( i used an image with the type set to Filler (horizontal). I already have the code working and everything, I just have the positioning issue
Answer by jmack · Sep 06, 2014 at 10:29 PM
I had this same issue, like AleKahpwn said I have resorted to setting the Canvas component position via code:
var canvas = gameObject.FindInChildren("Canvas");
var canvasePos = canvas.GetComponent<RectTransform>();
canvasePos.localPosition = new Vector3(0,8,0);
var objectName = gameObject.FindInChildren("PlayerNameText");
var playerName = objectName.GetComponent<Text>();
playerName.text = "FINALLY";
public static GameObject FindInChildren(this GameObject go, string name)
{
return (from x in go.GetComponentsInChildren<Transform>()
where x.gameObject.name == name
select x.gameObject).First();
}
Agreed... same things happening to me. I position everything nicely, create a prefab, then on instantiate the positions of some elements in the canvas are in the center of the canvas, not where I placed them. I'm thinking repositioning in script is the only workaround. I wonder if this is just a beta bug...