Skip to content

Instantly share code, notes, and snippets.

@avrahamy
Last active November 11, 2021 10:33
Show Gist options
  • Save avrahamy/1667a74eed54503b4d3305b70c635963 to your computer and use it in GitHub Desktop.
Save avrahamy/1667a74eed54503b4d3305b70c635963 to your computer and use it in GitHub Desktop.
Random animations sequence utility
using UnityEngine;
using System;
using Spine;
using Spine.Unity;
namespace GentleGiant.Animation {
public class SpineRandomAnimationsSequence : MonoBehaviour {
[Serializable]
public class AnimationChance {
[SpineAnimation(dataField = "skeletonAnimation")]
public string animationName;
public float chance;
public int maxRepeats;
[NonSerialized]
public int repeats;
}
[SerializeField] SkeletonAnimation skeletonAnimation;
[SerializeField] AnimationChance[] animations;
private AnimationChance lastAnimation;
protected void Start() {
skeletonAnimation.AnimationState.Complete += SkeletonAnimationStateOnComplete;
PlayAnimation();
}
private void SkeletonAnimationStateOnComplete(TrackEntry trackEntry) {
PlayAnimation();
}
private void PlayAnimation() {
var animationEntry = ChooseRandomWithChances(animations);
if (lastAnimation == animationEntry && lastAnimation.maxRepeats > 0) {
++lastAnimation.repeats;
if (lastAnimation.repeats >= lastAnimation.maxRepeats) {
while (lastAnimation == animationEntry) {
animationEntry = ChooseRandomWithChances(animations);
}
lastAnimation.repeats = 0;
animationEntry.repeats = 0;
}
} else {
animationEntry.repeats = 0;
}
lastAnimation = animationEntry;
skeletonAnimation.AnimationState.SetAnimation(0, animationEntry.animationName, false);
}
/// <summary>
/// Chooses a random element from the array.
/// Chance values don't have to sum to 1.
/// </summary>
public static AnimationChance ChooseRandomWithChances(AnimationChance[] array) {
var sumChance = 0f;
foreach (var t in array) {
sumChance += t.chance;
}
var rnd = UnityEngine.Random.value * sumChance;
foreach (var t in array) {
rnd -= t.chance;
// Checking for less than 0 so if rnd was 0, something with 0 chance
// won't get picked.
if (rnd < 0f) {
return t;
}
}
return array[array.Length - 1];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment