Reputation: 11
I'm spawning a prefab on MotherSpawner
gameObject and I want to spawn that prefab again on 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?
Upvotes: 0
Views: 691
Reputation: 242
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.
Upvotes: 0
Reputation: 12004
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
. 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. 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.
Upvotes: 1