コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Unity 2019.4 以前でスクリプトから Preset を適用する時にパラメータの除外を指定できる関数

ソースコード

using System.Linq;
using UnityEditor.Presets;
using UnityEngine;

public static class PresetUtils
{
    public static void ApplyToWithExclusion
    (
        Preset          preset,
        Object          target,
        params string[] excludedPropertyPaths
    )
    {
        var selectedPropertyPaths = preset.PropertyModifications
            .Select( x => x.propertyPath )
            .Where( x => !excludedPropertyPaths.Contains( x ) )
            .ToArray();

        preset.ApplyTo( target, selectedPropertyPaths.ToArray() );
    }
}

使用例

using UnityEditor;
using UnityEditor.Presets;

public static class Example
{
    [MenuItem( "Tools/Hoge" )]
    private static void Hoge()
    {
        var path      = "Assets/Transform.preset";
        var preset    = AssetDatabase.LoadAssetAtPath<Preset>( path );
        var transform = Selection.activeTransform;

        PresetUtils.ApplyToWithExclusion
        (
            preset,
            transform,
            "m_LocalPosition.x",
            "m_LocalPosition.y",
            "m_LocalPosition.z"
        );
    }
}

関連記事