how to reference uninstantiated prefab?

I have a script that gets attached to a game object through code when the time is right. The script instantiates another game object (an emitter) from a prefab. However, I can't seem to figure out the best way to reference the prefab that I want to instantiate.

I have tried using a var and assigning the prefab to the picker for the script, but since the script isn't attached to an object yet, this doesn't work (although it seems like it should). The "default references" for the script is assigned, but isn't honored by Unity when I AddComponent() the script.

In case you're wondering why, the script component isn't part of the object by default because the object doesn't need the behavior until a certain thing happens. In this case, it is a treasure object and it just sits there until the player picks it up. When the player picks it up, I add the CollectTreasure script, which handles everything related to picking it up, including instantiating a one-off emitter to show some sparkles when picked up.

Interesting. Are you not attaching that script for memory or performance reasons? I'm just wondering why.

I don't think I understand the question. The script is attached to the treasure on an as-needed basis, which is when the treasure gets picked up. The script handles animation and visual effects of picking up the treasure, which is only needed when picked up.

2 Answers

2

Attach the script to your object but disable it (untick the box) and assign all the prefabs. Then when you do need it to be enabled use the following:

GetComponent(YourScript).enabled = true;

'disable it' where 'it' is the script, not the object (just to be clear)

Interesting idea. Ironically, the component can't be found with GetComponent() when it is disabled, so there is no way to re-enable it unless I have previously saved a reference to it in a variable, which defeats the whole purpose. In addition, I would have to rig up each and ever prefab this way, which isn't feasible since there will be too many. Doing it dynamically in code is the only way.

Instead of assigning it in the picker, can you use Resources.Load?

That's actually what I'm forced to do right now, but it seems wrong that I can't get a reference to a prefab without attaching it or using Resources.Load. There has to be a way.

Resources.Load gives you a reference. It's that, or instantiate one in the scene, but I have heard this complaint before, you could vote for it a feedback.unity3d.com