- Home /
Get the name of an instance's prefab at runtime?
For savegame purposes I want to be able to access the name of an in-scene prefab's master-prefab name.
I want to do this so that the savegame code knows which resource to load, using the Resources.Load() function.
I don't want to rely on the GO's name, since that could be renamed in the scene and break the link. I also don't want to have to enter it by hand for all my GOs, since that would be error-prone.
Since prefab instances are linked to their masters (at least in the editor), is there a way to access this information programatically?
Answer by Statement · Dec 06, 2011 at 10:29 AM
There is no way that I know of. Maybe you could programatically add a utility component each time you instantiate a prefab though Resources.Load that store the name of the prefab?
Something like this?
function LoadPrefab(var path : String) : GameObject
{
var obj : GameObject = (GameObject)Resources.Load(path);
var tracker : PrefabTracker = obj.AddComponent(PrefabTracker);
tracker.path = path;
return obj;
}
Well that would work when using resources.load() because by that point we already know the path.
$$anonymous$$y issue if for placing items in a scene that might go into a player's inventory. For example, on level 1, the player may pickup a Gun prefab called LazerGun001. It's hand-placed in the scene and doesn't use Load().
In level 2 he saves the game while holding this gun. Now, we can't assume LazerGun001 exists in level 2. it may only be found in level 1.
so at the point of savegame, at a point where resources.load() has never been called, savegame needs to know the name of the resource so that loadgame can load the right gun. There's a few solutions to this:
when dragging the LazerGun001 prefab from resources to the scene, don't rename it and use gameObject.name for the path.
make the resources prefab have a "resourceName" variable that I hand-set per master prefab, and make it match the asset path.
Same as #2, but make it happen automatically.
something clever I'm not thinking of.
Number 1 is out of the question for me. Too much opportunity for messing it up and makes subfolders harder.
Number 2 is prone to user error but much less so. This is my best working bet so far.
Number 3 is what I'm hoping for at the moment.
Thanks for the help!
Your answer
Follow this Question
Related Questions
Why my prefab is auto changing? 3 Answers
Very Slow (hang) gameobject TO prefab operation with lot of child objects 0 Answers
How can I tell what prefab a GameObject belongs to? 2 Answers
Issues with tracking prefab instances and gameobject naming (JS) 1 Answer
Automatically update prefab instance 1 Answer