LoginSignup
1
1

More than 5 years have passed since last update.

Animatorのパラメタ関連処理をラップする

Last updated at Posted at 2016-09-16

アニメーターのパラメタ管理をするときに毎回同じようなコードを書いていたことに気づく...

Hashを保存したり、Animator.SetIntやGetIntしたり...

ということで以下のクラスを作ってみました。
HashIdのキャッシュやAnimatorのSetとGet処理を隠蔽しています
サポートしている型はAnimatorの仕様に従い、int float boolのみ

using System;
using UnityEngine;

/// <summary>
/// アニメーターのパラメタ
/// </summary>
public class AnimatorParam<T> where T : struct
{
    /// <summary>パラメタ名</summary>
    public string ParamName { get; set; }

    /// <summary>値. Setterで自動的にAnimatorパラメタが更新されます.</summary>
    public T Value
    {
        get { return (T)_value; }
        set { _value = value; }
    }

    /// <summary>パラメタのHash値.</summary>
    public int HashId
    {
        get
        {
            if (!_hashId.HasValue)
            {
                _hashId = Animator.StringToHash(ParamName);
            }
            return _hashId.Value;
        }
    }

    private object _value
    {
        get
        {
            if (typeof(T) == typeof(int)) return _animator.GetInteger(HashId);
            if (typeof(T) == typeof(float)) return _animator.GetFloat(HashId);
            if (typeof(T) == typeof(bool)) return _animator.GetBool(HashId);
            throw new NotSupportedException("Animator Param not support " + typeof(T).Name);
        }

        set
        {
            if (value is int) _animator.SetInteger(HashId, (int)value);
            else if (value is float) _animator.SetFloat(HashId, (float)value);
            else if (value is bool) _animator.SetBool(HashId, (bool)value);
            else throw new NotSupportedException("Animator Param not support " + typeof(T).Name);
        }
    }

    private int? _hashId;
    private Animator _animator;

    public AnimatorParam(Animator animator, string paramName)
    {
        ParamName = paramName;
        _hashId = Animator.StringToHash(ParamName);
        _animator = animator;
    }

    public AnimatorParam(Animator animator, string paramName, T initialValue)
    {
        ParamName = paramName;
        _hashId = Animator.StringToHash(ParamName);
        _animator = animator;
        Value = initialValue;
    }
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1