So as far as I know, there are 2 ways to attach a prefab reference to a variable in a script:
-
Drag the prefab into the public variable through the inspector; Problem: The reference is lost when the script is instantiated at run time.
-
Load the prefab by string name with resources.load(); Problem: Renaming or moving the script requires you to edit the name or path of the string passed into resources.load() in every location that loads that prefab.
Is there really no way to reference a prefab without having either of these issues?
The best solution I’ve come up with is to use resources.load but instead of passing in the string directly, pass a string variable containing the string from one globally accessible location (so renaming/moving the prefab means I only have to change the name/path at one location in code). This means that for every gameobject i might want to instantiate at run time, I’d need to add a variable in global scope reference that object’s prefab. While this is fine, it just seems a bit dirty, tedius, and unexpected to have to do in unity. I feel like there must naturally be a better way that I just don’t know about.
My specific situation:
I’m making an rpg. There are items in the form of scripts that are instantiated at run time. Some items need to instantiate gameobjects (like projectiles or art assets like a model of that item). So logically, they need a reference to that gameobject, which is a prefab.
Originally I manually dragged the prefabs the item needs to public variables in that item script through the inspector (which is an easy workflow). But when I instantiate the item at run time, the variables are cleared. The only time it doesn’t clear and actually maintain it’s value (the reference to the prefab) is when I drag the item into the scene in edit mode. But I need to add them to the scene at run time, not before hand in edit mode.