- Home /
Modify Prefab Asset in OnValidate
Hi, I'm trying to automatically assign a value to a field on a component that resides in a prefab in script and save that prefab modification in OnValidate.
Here is my script:
[SerializeField] MyComponent myComponent;
void OnValidate()
{
if (myComponent != null)
{
myComponent.myScriptableObject = this;
PrefabUtility.RecordPrefabInstancePropertyModifications(myComponent.myScriptableObject);
//At this point, myComponent.myScriptableObject shows the correct value
PrefabUtility.SavePrefabAsset(myComponent.gameObject, out bool success);
//Now myComponent.myScriptableObject is reset to null
}
}
Unfortunately, this script doesn't work. For some reason the value is not actually applied to the prefab. What am I missing here?
Also, calling SavePrefabAsset() in Onvalidate gives me the following error in console :
Destroying GameObjects immediately is not permitted during physics trigger/contact, animation event callbacks or OnValidate. You must use Destroy instead.
UnityEditor.PrefabUtility:SavePrefabAsset(GameObject, Boolean&) (at ?)
ResearchTree.Data.ResearchItem:OnValidate()
Is this related in any way?
Answer by FredTuna · Jan 15, 2020 at 09:30 PM
In case others were looking for that answer. This is what I ended up doing:
SerializedObject serializedObject = new SerializedObject(myComponent);
SerializedProperty myComponentProperty = serializedObject.FindProperty("myProperty");
if (myComponentProperty != null)
{
myComponentProperty.objectReferenceValue = this;
serializedObject.ApplyModifiedProperties();
}
Answer by Esteem · Jan 16, 2020 at 09:18 PM
What are you actualy trying to do? There's something fishy about what you showed ...
I'm just trying to set a serialized field of a component on a prefab to a certain value from a scriptable object's OnValidate.
Your answer
Follow this Question
Related Questions
How to find the prefab base of a Prefab Variant through code? 1 Answer
Why does CreateEmptyPrefab return null? 1 Answer
How to check if an object is asset in build runtime (Not in Editor) ? 4 Answers
Safely deleting a child of a prefab 1 Answer
Need to make a reference in a prefab to itself not to the created instance 2 Answers