简体   繁体   English

Unity Spawning Prefab

[英]Unity Spawning Prefab

I'm trying to spawn a prefab using script. 我正在尝试使用脚本生成预制件。 This is the code, the code is written inside the game panel. 这是代码,代码写在游戏面板内。

Network.Instantiate (ninjaPreFab, new Vector3 (-53, -34, 0), Quaternion.identity, 0);

However, it is not spawning within the canvas. 但是,它不会在画布中生成。 Instead it always spawn outside of the canvas which mean it's not a child of the canvas, thus not appearing inside the game as I'm using Rendering - Overlay Camera. 相反,它总是在画布之外产生,这意味着它不是画布的孩子,因此不会出现在游戏内部,因为我正在使用渲染 - 叠加相机。 I've tried setting the Sort Order for the canvas to be -1 but still it doesn't work. 我已经尝试将画布的排序顺序设置为-1但仍然不起作用。 I know it spawned because the editor clearly show that there is this new object. 我知道它产生了,因为编辑清楚地表明存在这个新对象。

If using the new Unity UI, GUI elements must be a child of the canvas gameobject and their coordinates must be set within the boundaries of the canvas and not too close to the camera near-clipping plane (within the viewing frustum) if they are to be visible on screen. 如果使用新的Unity UI,GUI元素必须是画布游戏对象的子元素,并且它们的坐标必须设置在画布的边界内,并且不要太靠近相机近剪裁平面(在视锥体内),如果它们是在屏幕上可见。 If working with the UI canvas, have a look at the awesome Unity UI tutorials here . 如果使用UI画布,请在此处查看令人敬畏的Unity UI教程。

As per your snippet of code, it appears your UI elements are invisible because of the negative sign on the coordinate values. 根据您的代码片段,由于坐标值上的负号,您的UI元素看起来是不可见的。 Try changing them to positive values and see what happens. 尝试将它们更改为正值,看看会发生什么。 Also, parent the UI element to the canvas like this: 另外,将UI元素添加到画布,如下所示:

var newUIElement = Network.Instantiate (ninjaPreFab, new Vector3 (53, 34, 0), Quaternion.identity, 0);
newUIElement.transform.parent = canvas;

Problem solved. 问题解决了。 I wasn't supposed to spawn game object/sprite inside the canvas. 我不应该在画布中生成游戏对象/精灵。 Canvas is only meant for UI. Canvas仅适用于UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM