Skip to content

Instantly share code, notes, and snippets.

@HilariousCow
Last active August 12, 2021 23:39
Show Gist options
  • Save HilariousCow/00130c39174432f10f67fb9782a4e956 to your computer and use it in GitHub Desktop.
Save HilariousCow/00130c39174432f10f67fb9782a4e956 to your computer and use it in GitHub Desktop.
AnimParam TidyUp code - so that your controller scripts aren't dripping in hashed versions of Animator parameters.
class MyControllerComponent : MonoBehaviour{
Animator _anim;
AnimParam _myTrigger;
void Awake()
{
_anim = GetComponent<Animator>();
_playbackDurations = GetComponent<PlaybackDurationManager>();
_myTrigger = _anim.AnimParam("StartThings");
}
void Update()
{
if(/*something*/)
{
_myTrigger.SetTrigger();
//can also be used as bool, float, int
//Just make sure the param set up in the Animator is of the same type.
}
}
}
public class AnimParam
{
private readonly int _hashed;
private readonly string _paramName;//don't really need but good for debug?
private readonly Animator _anim;
private float _floatValue;
public float FloatValue { get { return _floatValue; }
set
{
SetFloat(value);
}
}
private bool _boolValue;
public bool BoolValue
{
get { return _boolValue; }
set
{
SetBool(value);
}
}
private int _intValue;
public int IntValue
{
get { return _intValue; }
set
{
SetInt(value);
}
}
public string ParamName
{
get { return _paramName; }
}
public int Hashed
{
get { return _hashed; }
}
public AnimParam(Animator animator, string param)
{
if (animator == null) Debug.LogError("Animator is null");
_anim = animator;
_paramName = param;
_hashed = Animator.StringToHash(param);
}
public void SetFloat(float val)
{
_floatValue = val;
if (_anim.isActiveAndEnabled)
{
_anim.SetFloat(Hashed, val);
}
}
public void SetBool(bool val)
{
_boolValue = val;
if (_anim.isActiveAndEnabled)
{
_anim.SetBool(Hashed, val);
}
}
public void SetInt(int val)
{
_intValue = val;
if (_anim.isActiveAndEnabled)
{
_anim.SetInteger(Hashed, val);
}
}
public void SetTrigger()
{
if (_anim.isActiveAndEnabled)
{
_anim.SetTrigger(Hashed);
}
}
public void ResetTrigger()
{
if (_anim.isActiveAndEnabled)
{
_anim.ResetTrigger(Hashed);
}
}
public override string ToString()
{
return _paramName;
}
}
public static class AnimationExtentions {
public static AnimParam AnimParam(this Animator anim, string ParamName)
{
return new AnimParam(anim, ParamName);
}
}
@bloodchild8906
Copy link

lol I just saw hat this code was written 5 years ago was going to say that it really needed a refactor lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment