- Home /
Instantiate Prefab (Image) and show it on the screen?
I notice that after I instantiated the prefab (which is an UI Image) and set its position, it is added to the root level in the hiearchy which somehow doesn't appear on the screen. However, during run time, if I drag this image (clone) to the Canvas then I see it.
Could someone explain this behavior and is it that I have to manually add the image to the canvas in order to see it (if so how)?
(edited)
I figured out how to add the instantiated object to the target object within the canvas by setting transform parent, but for some reason the position of the instantiated object is not entirely correct: Say the parent has transform.position as (227.2, 316.5, 0) and the child (instantiated object) has the transform.position as (-10, -10, 0)
That is I notice the origin of child transform is not identical to its parent in this case, regardless of how I reset the parent and the child of the target object and the moved object itself, but still its being offset by a lil bit, so Im not sure whats going on
Answer by Garazbolg · Oct 13, 2015 at 12:31 PM
When do your Instantiate you can define a position :
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
There you can define the position of your Image.
But when you will parent him to your Canvas you should Use the function SetParent of Transform because you have a second argument that specify if you want your Transform not to change Global position ( http://docs.unity3d.com/ScriptReference/Transform.SetParent.html ).
Hope that will fix your problem.
Thank you. I spent quite some time last night to figure out how to solve the issue and I read thru many valuable tips including yours. I end up using localPosition zero for the child after set its parent. One strange behavior that I notice is that this only work (both using position or localposition) if I set both parent and child pivot to center. Otherwise (any other pivot say left-down) it still gives me some offset even though the rect transform for the child in inspector shows 0,0,0.
I created another question right here if you dont $$anonymous$$d http://answers.unity3d.com/questions/1081039/child-object-local-position-keeps-getting-offset-w.html