- Home /
Is there a way to edit an instantiated prefab without modifying the prefab itself?
Hey Everybody, I am instantiating a prefab using an editor script. Then, I am modifying the instantiated object (say, adding a rigidbody to it). This should work, but it's actually modifying the prefab, rather than the instantiation of it. Am I missing something obvious here? Please help out. Here is a sample of the code:
UnityEngine.Object prefabObject = AssetDatabase.LoadAssetAtPath(newObjectFullPath, typeof(GameObject));
GameObject newObject = Instantiate(prefabObject) as GameObject;
newObject.AddComponent<Rigidbody2D>();
So, am I missing anything here? I am running this from an editor script, so maybe there is a bug there? I've read that people have made this work from editor scripts...
Thanks!
Answer by Bunny83 · Sep 10, 2016 at 12:56 PM
You should not use Instantiate in editor code unless that really is what you want to do. Instantiate just creates a clone of the source object and does not remember the prefab reference.
To create a prefab instance inside the editor you should use PrefabUtility.InstantiatePrefab.
Hi, thanks for the quick reply!
Unfortunately, I have tried all variations of instantiate, to no avail...
This is my current code (using PrefabUtility.InstantiatePrefab), and I am seeing the same results:
UnityEngine.Object prefabObject = AssetDatabase.LoadAssetAtPath(newObjectFullPath, typeof(GameObject));
GameObject newObject = PrefabUtility.InstantiatePrefab(prefabObject) as GameObject;
newObject.AddComponent<Rigidbody2D>();
Am I doing it wrong?
So, I think this is actually a bug in Unity. I just moved my prefab to the Resources folder and called Resources.Load, rather than AssetDatabase.LoadAssetAtPath. This works now. Has anyone seen this issue before? Is there a reason for it? I think this is a bug for sure...
This code does not work:
UnityEngine.Object prefabObject = AssetDatabase.LoadAssetAtPath(newObjectFullPath, typeof(GameObject));
GameObject newObject = PrefabUtility.InstantiatePrefab(prefabObject) as GameObject;
newObject.AddComponent<Rigidbody2D>();
This code works:
UnityEngine.Object prefabObject = Resources.Load(instance.type, typeof(GameObject));
GameObject newObject = PrefabUtility.InstantiatePrefab(prefabObject) as GameObject;
newObject.AddComponent<Rigidbody2D>();
Answer by Jonesy19 · Sep 10, 2016 at 10:39 PM
Okay, with more debugging, it looks like this was an error on my part. There was another part of my script that was causing this issue. It looks like it works fine. Sorry to anyone who read through this.