Skip to content

Instantly share code, notes, and snippets.

@rutcreate
Last active July 21, 2016 10:32
Show Gist options
  • Save rutcreate/ae67b65c384fbd6b1279 to your computer and use it in GitHub Desktop.
Save rutcreate/ae67b65c384fbd6b1279 to your computer and use it in GitHub Desktop.
Unity3D: Broadcast message to all object in state machine behaviour.
using System.Text.RegularExpressions;
using UnityEngine;
public class AnimationBroadcastStateMachineBehaviour : StateMachineBehaviour {
// Could not find the way to get current state name.
// So end up with this. Define variable again.
public string stateName;
// Clean up white space before use.
public string StateName {
get {
return Regex.Replace(stateName, @"\s+", "");
}
}
public bool onStateEnter;
public bool onStateExit;
public bool onStateMove;
public bool onStateUpdate;
public bool onStateMachineEnter;
public bool onStateMachineExit;
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateEnter", StateName), new StateMachineBehaviourArgs(animator, stateInfo, layerIndex, StateName));
}
}
public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateExit", StateName), new StateMachineBehaviourArgs(animator, stateInfo, layerIndex, StateName));
}
}
public override void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateMove", StateName), new StateMachineBehaviourArgs(animator, stateInfo, layerIndex, StateName));
}
}
public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateUpdate", StateName), new StateMachineBehaviourArgs(animator, stateInfo, layerIndex, StateName));
}
}
public override void OnStateMachineEnter(Animator animator, int stateMachinePathHash) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateMachineEnter", StateName), new StateMachineBehaviourArgs(animator, stateMachinePathHash, StateName));
}
}
public override void OnStateMachineExit(Animator animator, int stateMachinePathHash) {
if (!string.IsNullOrEmpty(StateName)) {
Broadcast(string.Format("On{0}StateMachineExit", StateName), new StateMachineBehaviourArgs(animator, stateMachinePathHash, StateName));
}
}
private void Broadcast(string functionName, object arg = null) {
var gameObjects = GameObject.FindObjectsOfType<GameObject>();
foreach (var go in gameObjects) {
// Only root game object.
if (go && go.transform.parent == null) {
go.BroadcastMessage(functionName, arg, SendMessageOptions.DontRequireReceiver);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment