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?

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;