I am trying to load, at run time, a UI prefab and have that display on a canvas. I was following the directions found on this forum. I am able to get it to load and display, but it is not showing up correctly, as shown here:
If I manually change the position in the Unity editor, at runtime, then it appears correct, as shown here.
Here's my code:
// load the prefab
Object subView = Resources.Load($"prefabs/Tutorial-Info");
// find the attach point (see screen shot for child hierarchy)
GameObject panel = SearchFor("Panel");
var subPanel = Instantiate(subView, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
subPanel.transform.SetParent(panel.transform, false);
(SearchFor
is a function I wrote to find canvas objects by name. It is correctly returning "Panel" object. The code that function is here.)
I am not sure why the prefab instantiated at run time is not appearing where I want it to appear. What should I do?
Instantiate(subView, panel.transform)
to spawn it directly into the desired parent, rather than spawning it at world-0,0,0 then moving it? Also note thattransform.position = new Vector3(0,0,0)
says "figure out what local position is needed to push this thing to the world origin (bottom left of the screen) and do that" — so it looks like this code is doing exactly what you asked it to do. Why ask to put the object at the world origin if that isn't what you wanted? Do you need that last line at all? \$\endgroup\$