如何在另一个游戏对象上生成预制件 [英] How to spawn prefab on another gameobject

查看:92
本文介绍了如何在另一个游戏对象上生成预制件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在MotherSpawner gameObject 上生成一个预制件,我想再次在positionWhereObjectSpawn gameObject 上生成该预制件.

I'm spawning a prefab on MotherSpawner gameObject and I want to spawn that prefab again on positionWhereObjectSpawn gameObject.

我打算做的是使用GameObject.Find获取positionWhereObjectSpawn gameobject 的位置,然后在该位置上生成,但他们说这样效率不高.

What I'm planning to do is get the position of positionWhereObjectSpawn gameobject using GameObject.Find, then spawn on that position, but they say it's inefficient.

执行此操作的有效方法是什么?

What's the efficient way to do this?

推荐答案

类似的方法应该起作用:

Something like this should work:

var posGo = GameObject.Find("positionwhereobjectspawn");
Instantiate(myPrefab, posGo.transform.position, posGo.transform.rotation);

在这里效率低下的一件事是GameObject.Find.如果您在每次生成时都这样做,是的,它的效率很低.如果您一次找到它,然后简单地将其放入类中的变量中以备后用,那么它会很有效.像这样:

One thing that's inefficient here is the GameObject.Find. If you do it at every spawn, yes, it is inefficient. If you find it once and simply place it into a variable in your class to be used later, it's efficient. Like so:

GameObject posGo;
Start() {
  posGo = GameObject.Find("positionwhereobjectspawn");
}

Update() {
  if(Input.GetKeyDown(KeyCode.SPACE)) {
    Instantiate(myPrefab, posGo.transform.position, posGo.transform.rotation);
  }
}

提高效率的下一步是摆脱Instantiate并使用对象池.您可以预先创建游戏对象,隐藏它们,并在需要时使用它们.为此,您应该使用Google统一对象池并使用其中一个选项.

Next step to improve efficiency is to get rid of the Instantiate and use an object pool. You create game objects in advance, hide them, and use them when needed. For that, you should Google unity object pooling and use one of the options.

这篇关于如何在另一个游戏对象上生成预制件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆