- Home /
Changes to prefab instance generated from script aren't remembered
In an Editor script I spawned a linked instance to a prefab, but all changes i make to it are ignored (not reflected in the scene).
GameObject gameObj = PrefabUtility.InstantiatePrefab(myPrefabObj) as GameObject;
// does nothing
gameObj.name = "test";
gameObj.transform.localPosition = pos;
gameObj.transform.localScale = scale;
However, if I use GameObject gameObj = Instantiate(myPrefabObj) as GameObject;
, everything works fine (except the instance isn't linked to the prefab).
I verified that myPrefabObj is a Prefab GameObject and gameObj is a PrefabInstance (by using PrefabUtility.GetPrefabType).
What could I be doing wrong?
you need to click apply in the inspector after you make changes... idk if you've done that if not that could be the problem
I'm trying to affect the instance itself from c#, not the prefab. Setting the name of the gameobject instance does nothing (the name remains unchanged). Using "Instantiate" works fine for some reason.
Answer by Bunny83 · Jul 21, 2018 at 09:11 AM
Like with all editor script which modify serialized data you have to tell the serialization system about the change. Usually for objects in the scene you would use Undo.RecordObject before you do your changes. Basically like this:
GameObject gameObj = PrefabUtility.InstantiatePrefab(myPrefabObj) as GameObject;
Undo.RecordObject(gameOb, "Changed object properties");
gameObj.name = "test";
gameObj.transform.localPosition = pos;
gameObj.transform.localScale = scale;
Though in your case Undo.RegisterCreatedObjectUndo may work as well like this:
GameObject gameObj = PrefabUtility.InstantiatePrefab(myPrefabObj) as GameObject;
gameObj.name = "test";
gameObj.transform.localPosition = pos;
gameObj.transform.localScale = scale;
Undo.RegisterCreatedObjectUndo(gameObj, "Created instance");
If nothing works you can always use EditorSceneManager.MarkSceneDirty. Though you should use this only in extreme cases. It will always mark the scene dirty and will force the user to save the scene regardless of any changes.
Undo.RecordObject was exactly what I needed. Thanks for the help
Your answer
Follow this Question
Related Questions
Don't allow prefab to spawn if prefab already exists at the spawn location. 1 Answer
How to randomly instantiate other prefabs parallel? 1 Answer
Why is instantiated animator prefabs are not working properly? 2 Answers
How do i Instantiate a prefab with specific assests included 3 Answers
ID or name for Instantiate prefab 1 Answer