Instantiating from an Instance (copy of a copy) loses variable values

Say I have 5 different types of enemies.

On game startup, I instantiate one copy of each of them.

I then run a bunch of scripts on each of those instances to “prep” them for gameplay (adding fx, hooking up AI, creating collision boxes, etc.)
Then, when I actually need one of those enemies in the game, I instantiate the “prepped” instance.

Sure, I could run all of the prep work on each instance as I spawn it, but there’s a framerate hit when doing so, so why not just do it once?

The problem: Many of the variables that I’ve set during the “prep” phase are lost during the second Instantiation. Mainly seems to be variables pointing to other components on/under the object, like collision.

E.g. in my “prep” stage, I’ll set

m_visibilityCollision = transform.Find("VisColl").GetComponent<BoxCollider>();

But when I instantiate the “prepped” instance, m_visibilityCollision is null.

How can I ensure Instantiate creates a full copy of a modified source prefab?

Thanks for any suggestions!

-Scott

Is m_visibilityCollision a serializable field? Unity can only copy serializable data. This is pretty much the same set of fields that shows up in the object’s inspector.

While you’re at it, instead of using transform.Find, would it be a hassle to just drag and drop these references in the inspector for the prefab (do they exist at design time?)? That would be faster than running transform.Find and GetComponent at runtime.

2 Likes

I was going to say the same thing on the transform.Find. Generally if I have a prefab and it has children on it that need to be hooked into a script on the top parent, I just drag and drop and connect it that way. Especially if you’re looking at having to do several transform.Find to setup the object and it’s creating a “hiccup” when you do so.

1 Like

Ah! m_visibilityCollision (and the other problem vars) are Internal fields, rather than Public, which is why they weren’t serializing. Now that I’ve tagged them with [SerializeField] they’re being set correctly. Thank you!

As for the Transform.Find, I’m only using that for items that don’t yet exist or may not be set depending on game variables (difficulty settings, player options, game modes, etc.). Stuff that I’m either dynamically creating on game start or can’t necessarily assume should exist, therefore can’t rig up in the prefab.

1 Like