- Home /
Most efficient way to get a reference to a gameobject near NPC?
Every time an NPC spawns, I need to get a reference to the spawner object that spawned them. I can't get this through the script itself, as the system that pools and spawns/despawns NPCs can't talk to them, it simply selects a random index from the list of active spawners and spawns the NPC at those coordinates.
Depending on what else is going in the vicinity, this can lead to the NPC spawning at an unpredictable offset from the spawner object, meaning that SpawnTransform.gameobject will not consistently return the spawner.
As such, what's the simplest way I can grab a reference to the spawner? I thought about using a spherecast and iterating through the colliders it returns until I find one with the right tag, but this will potentially happen upwards of 10x/second, so I don't want to start casting and checking lists if I don't have to. Another option would be to find the spawner from my list of active spawners with the least distance to the NPC, but that again involves more math and list sorting than I want to be doing regularly. Is there an efficient solution I'm missing, or is it worth reworking my pooling system so it can directly message the NPC as it spawns them?
Answer by KulestarUK · Nov 19, 2014 at 09:10 AM
I believe the link you're missing is a npcObject.GetComponent() call.
When you spawn an NPC, you must have a reference to both the NPC and be aware which spawner you used. Assuming your NPC is a prefab, it probably also has a script attached to it - for now we'll also assume that this script is the one that wants to know which spawner it came from.
Let's call this script NpcController, and it has a property called SpawnerObject:
public GameObject SpawnerObject;
Your spawner script should then look something like this:
// Select a spawner:
GameObject spawner=ActiveSpawners[theRandomNumber];
// Spawn:
GameObject newNPC=GameObject.Instantiate(theNpcPrefab,spawner.transform.position,Quaternion.identity);
// That magic line - grab the NpcController script on the spawn:
NpcController controller=newNPC.GetComponent<NpcController>();
// Hook up the SpawnerObject:
controller.SpawnerObject=spawner;
Your answer
![](https://koobas.hobune.stream/wayback/20220613171908im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Position of a cloth? 2 Answers
[Closed]transform.position not updating fast enough 0 Answers
Distribute terrain in zones 3 Answers
C# Smoothing Out transform.Translate 4 Answers