简体   繁体   English

如何在另一个游戏对象上生成预制件

[英]How to spawn prefab on another gameobject

I'm spawning a prefab on MotherSpawner gameObject and I want to spawn that prefab again on positionWhereObjectSpawn gameObject .我在MotherSpawner gameObject上生成一个预制件,我想在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.我打算做的是使用GameObject.Find获取positionWhereObjectSpawn GameObject.Find对象的位置,然后在该位置生成,但他们说它效率低下。

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);

One thing that's inefficient here is the GameObject.Find .这里效率低下的一件事是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);
  }
}

Next step to improve efficiency is to get rid of the Instantiate and use an object pool.提高效率的下一步是摆脱Instantiate并使用对象池。 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.为此,您应该谷歌统一对象池并使用其中一个选项。

If this is static and you wont change the number of spawns you can do is make public fields and store the Transform of both the spots where you want to spawn a prefab just by making 2 public Transform fields OR if you want to increase the number of spawns you can simply store these positions in a collection and use that to spawn objects, and yea Gameobject.Find is inefficient, this method searches through your whole hierarchy so think how much time will it take to look through everything.如果这是静态的并且你不会改变生成的数量,你可以做的是创建公共字段并存储你想要生成预制件的两个点的转换,只需创建 2 个公共转换字段或者如果你想增加spawns 你可以简单地将这些位置存储在一个集合中并使用它来生成对象,是的 Gameobject.Find 是低效的,这个方法搜索你的整个层次结构所以想想看所有东西需要多少时间。

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

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