Search Unity

Delegate when Object is Converted to Prefab

Discussion in 'Prefabs' started by Thygrrr, Nov 8, 2018.

  1. Thygrrr

    Thygrrr

    Joined:
    Sep 23, 2013
    Posts:
    700
    Is there a way for to have code execute when the user drags an object from the hierarchy into the project browser to create a Prefab?

    Ideally BEFORE this happens. (I have a procedural mesh on a meshfilter, and in the moment it becomes a prefab I'd like to convert it into an asset so the prefab can be properly used - but most objects of that type will not be prefabs, so I shouldn't always save the procedural mesh as an asset)
     
  2. https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.OnWillCreateAsset.html
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CustomAssetModificationProcessor : UnityEditor.AssetModificationProcessor
    6. {
    7.     static void OnWillCreateAsset(string assetName)
    8.     {
    9.         Debug.Log("OnWillCreateAsset is being called with the following asset: " + assetName + ".");
    10.     }
    11. }
    12.  
    "OnWillCreateAsset is being called with the following asset: Assets/GameObject.prefab."

    Although I'm not sure if it's possible to change the course of creation at this point. You may want to try to postpone your changes after the asset has been created. But it's a start.
     
  3. Thygrrr

    Thygrrr

    Joined:
    Sep 23, 2013
    Posts:
    700
    I've hooked into PrefabUtility. prefabInstanceSaved, which kind of works, but requires applying the prefab one more time afterwards. I am also struggling with objects that are part of prefabs, but not the instance itself.

    The handler you showed has promise, but seems largely detached from the game objects and prefab instances.
     
  4. MatthieuPr

    MatthieuPr

    Joined:
    May 4, 2017
    Posts:
    56
    There should be a way to apply your prefab from script, I would suggest to look at PrefabUtility. So you could do the 2nd apply from the same script as well...