Referencing an object from an instantiated prefab (C#)

Hi.
I’m trying to something like this:
There is a “Police Department” prefab which instantiates “Cop” prefabs (this part works).
Police Department should keep track on how many cops have died and should spawn 2 new cops for every dead one. The “keeping track” part does not work.

My first instinct was to give cop prefabs script with

public GameObject _myPoliceDepartment;

and drag “Police Department” prefab into this slot in the editor. If I manually place cops on the scene, they can reference Police Department just fine.
But once I instantiate them, this field remains empty and I get the error:

Another thing is that there will be several police departments which spawn and track their cop independent from each other (if a cop from PD1 dies, it does not affect PD2 etc).

So my question is: how do I reference “police department” that has spawned a “cop” prefab from that instantiated cop prefab?

Thanks!

Without knowing more about your setup, I can only give you an idea. If your police departments have a script on them to spawn a cop (I’m thinking like an RTS where you select units to build), then when a police department spawns a cop(instantiates), you should be able to create a reference in the police department for the cop and also access some script on the cop that points back to the police department that spawned it.

think
GameObject cop = //instantiate the cop
cop.GetComponent().policeDepartment = gameobject; //Sets the cop policeDepartment to the police department that spawned it.

But again, not sure you setup, but this should give an idea.

1 Like

Thank you very much, this solved my problem.