Files
beyond/Assets/AI/_Gigant/RandomizeAnimatorIntOnEnter.cs
2025-11-20 14:34:59 +01:00

48 lines
1.0 KiB
C#

using UnityEngine;
public class RandomizeAnimatorIntWeighted : StateMachineBehaviour
{
[Header("Animator parameter name (must be int type)")]
public string parameterName = "Randomized";
[Header("Weights for each slot (index = int value)")]
public int[] weights = { 35, 35, 15, 15 };
// Example: {70, 20, 10} means index 0 has 70% chance, 1 has 20%, 2 has 10%
// Called when the animator enters this state
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (weights == null || weights.Length == 0)
{
return;
}
int total = 0;
foreach (int w in weights)
{
total += Mathf.Max(0, w);
}
if (total <= 0)
{
return;
}
int randomValue = Random.Range(0, total);
int cumulative = 0;
int chosenIndex = 0;
for (int i = 0; i < weights.Length; i++)
{
cumulative += Mathf.Max(0, weights[i]);
if (randomValue < cumulative)
{
chosenIndex = i;
break;
}
}
animator.SetFloat(parameterName, (float)chosenIndex);
}
}