Skip to content

Latest commit

 

History

History
48 lines (36 loc) · 1.36 KB

File metadata and controls

48 lines (36 loc) · 1.36 KB

UNT0041 Use Animator.StringToHash for repeated Animator method calls

Animator methods have overloads that accept either a string or an int (hash) parameter. Using the string-based overload repeatedly causes Unity to compute the hash every time, which impacts performance.

Examples of patterns that are flagged by this analyzer

using UnityEngine;

class Example : MonoBehaviour
{
    private Animator _animator;

    void Update()
    {
        // UNT0041: Use Animator.StringToHash for repeated Animator method calls
        _animator.Play("Attack");
        _animator.SetBool("IsRunning", true);
        _animator.SetFloat("Speed", 1.5f);
    }
}

Solution

Pre-compute the hash using Animator.StringToHash and store it in a static readonly field:

using UnityEngine;

class Example : MonoBehaviour
{
    private static readonly int AttackHash = Animator.StringToHash("Attack");
    private static readonly int IsRunningHash = Animator.StringToHash("IsRunning");
    private static readonly int SpeedHash = Animator.StringToHash("Speed");

    private Animator _animator;

    void Update()
    {
        _animator.Play(AttackHash);
        _animator.SetBool(IsRunningHash, true);
        _animator.SetFloat(SpeedHash, 1.5f);
    }
}

A code fix is offered for this diagnostic to automatically extract the string literal to a cached hash field.