0
\$\begingroup\$

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:

Text barely visible in corner of frame

If I manually change the position in the Unity editor, at runtime, then it appears correct, as shown here. Text appears correctly inside frame

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?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Have you tried 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 that transform.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\$
    – DMGregory
    Nov 15, 2023 at 19:30
  • \$\begingroup\$ I did not. And using your suggestion, Instantiate(subView, panel.transform), worked correctly. The last line was left over from a previous attempt. It is not needed. \$\endgroup\$
    – tatmanblue
    Nov 15, 2023 at 19:32

1 Answer 1

1
\$\begingroup\$

The correct solution is to use Instantiate as follows:

Object subView = Resources.Load($"prefabs/Tutorial-Info");
GameObject panel = SearchFor("Attach");
Instantiate(subView, panel.transform);

The call to SetParent is no longer needed and position setting was incorrect to begin with. Please see the comments above for a little more detail on the solution.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .