Community Made Tools

Have you made any useful utilities with Odin?

Login and submit your creations here

DisableInPrefabVariants Attribute

Authored by Lucas
Shared 01-05-2022

Just a simple attribute that disables a field in prefab variants, thus avoiding allowing overrides in fields you don't want to be changed from the original.

This works even on prefab stages.

Usage

    public class SampleScript : MonoBehaviour
    {
        [DisableInPrefabVariants]
        public int somethingToSetOnlyOnOriginalPrefab;

        public int overridableValue;
    }

DisableInPrefabVariantsAttribute.cs

    [AttributeUsage(AttributeTargets.Field)]
    public class DisableInPrefabVariantsAttribute : Attribute
    {
    }

DisableInPrefabVariantsAttributeStateUpdater.cs

[assembly: RegisterStateUpdater(typeof(DisableInPrefabVariantsAttributeStateUpdater))]

namespace DisableInPrefabVariants
{
    public class DisableInPrefabVariantsAttributeStateUpdater : AttributeStateUpdater<DisableInPrefabVariantsAttribute>
    {
        private bool _disable;

        protected override void Initialize()
        {
            var unityObjectTarget = Property.Tree.WeakTargets[0] as UnityEngine.Object;

            if (unityObjectTarget == null) return;

            var stage = PrefabStageUtility.GetCurrentPrefabStage();
            if (stage != null)
            {
                unityObjectTarget = stage.openedFromInstanceObject;
            }
            
            var type = PrefabUtility.GetPrefabAssetType(unityObjectTarget);
            bool isPartOfVariant = PrefabUtility.IsPartOfVariantPrefab(unityObjectTarget);
            _disable = type == PrefabAssetType.Variant || isPartOfVariant;
        }

        public override void OnStateUpdate()
        {
            if (Property.State.Enabled && _disable)
            {
                Property.State.Enabled = false;
            }
        }
    }
}
#endif