Unity prefabs are visible in the scene, and the invisible processing is copied through code.

First I made a prefab, which is visible in the scene, as shown below

Both the Scene view and the Game view are normal.

I put the prefab in Resources, and then I copied it to the same parent object through the following code.

 GameObject obj1 = Instantiate(Resources.Load("Butcon")) as GameObject;
 obj1.transform.SetParent(tran);
 obj1.transform.localScale = Vector3.one;

There is nothing wrong with the code. I set its parent object and then clamped its Scale to be the same as before.

Another thing is that I used the Grid Layout Group to clamp the width of the copied prefab to be the same as the original. As shown below,

Everything seems to be fine, and then running, the following effect appears:

The Scene view is normal and the position is normal, but the Game view is missing.

This is strange. I set the parent object in my code, and the width and height of the parent object are clamped through the Grid Layout Group. Then you can see that the Scene view is normal. The most important thing is that there is nothing in my scene, so I copy a prefab, so it is blocked. Also ruled out.

Then I checked to see if the camera settings, levels, or rendering factors were affecting it. I checked carefully one by one and found that there was nothing unusual.

It's really puzzling.

Later, I calmed down and thought that I should start with the camera.

Because the rendering mode in my actual application is through the camera, the problem should be related to the camera.

After taking a closer look, I suddenly discovered that because the project was being developed at the time, the 2D view was used. Then I thought about whether I should switch to the 3D view to see if I would find anything.

2D view

Sure enough, when I converted to 3D view, I immediately discovered the problem!

The original copied UI prefab is not under the camera. After this investigation, I found that even though I used the Grid Layout Group to clamp the width and height, and the Z coordinate of my prefab was 0, the Z coordinate I copied through the code became -2308.644.

It turns out that the coordinates of an object copied using Instantiate will change according to certain rules. It is not a copy of the coordinates of your prefab itself. Just like its Scale too!

So when we use code to generate an object and find an exception, we must first check whether the Scale and Position are reset when creating it.

If you use the following code and then run the program, it will be normal:

        GameObject obj1 = Instantiate(Resources.Load("Butcon")) as GameObject;
        obj1.transform.SetParent(tran);
        obj1.transform.localScale = Vector3.one;
        obj1.transform.localPosition = Vector3.zero;

Guess you like

Origin blog.csdn.net/mr_five55/article/details/134471034