Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by giraffe1 · Jan 20, 2016 at 04:59 PM · eventsstate-machinedelegates

Newbie State Machine Behaviours with Events and Delegates Questions

Hi,

The event is sending and I am seeing the debug lines perfectly but I have 1 yellow error and 1 red that I am having trouble understanding. Basically I am trying to use the state machine behavior to listen & send an event when it starts to play an shoot animation and when it ends.

This is my state machine behavior script: credit goes to: https://www.reddit.com/r/Unity3D/comments/39eh4x/tutorial_state_machine_behaviours_discouple/

 using UnityEngine;
 using System.Collections;
 
 public class StateMachineEvent: StateMachineBehaviour
 {
     public delegate void StateEventHandler(Animator animator, AnimatorStateInfo stateInfo, int layerIndex);
 
     public event StateEventHandler OnStateEntered;
     public event StateEventHandler OnStateExited;
 
     public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         base.OnStateEnter(animator, stateInfo, layerIndex);
 
         if (OnStateEntered != null)
         {
             OnStateEntered (animator, stateInfo, layerIndex);
         }
     }
 
     public virtual void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         base.OnStateExit(animator, stateInfo, layerIndex);
 
         if (OnStateExited != null)
         {
             OnStateExited (animator, stateInfo, layerIndex);
         }
     }
 }

This is my the script I have on my gameobject:

 using UnityEngine;
 using System.Collections;
 
 public class AIController: MonoBehaviour
 {
     private Animator animator;
 
     void Awake()
     {
         animator = GetComponent<Animator>();
     }
 
     void OnEnable()
     {
         animator.GetBehaviour<StateMachineEvent>().OnStateEntered += RifleOneShotStart;
         animator.GetBehaviour<StateMachineEvent>().OnStateExited += RifleOneShotEnd;
     }
 
     void RifleOneShotStart(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         Debug.Log("Rifle one shot - animation START");
     }
 
     void RifleOneShotEnd(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         Debug.Log("Rifle one shot - animation END");
     }
 
     void OnDisable()
     {
         animator.GetBehaviour<StateMachineEvent>().OnStateEntered -= RifleOneShotStart;
         animator.GetBehaviour<StateMachineEvent>().OnStateExited -= RifleOneShotEnd;
     }
 }

This is the yellow error that shows up when I am in the editor:

 Assets/Misc/StateMachineEvent.cs(21,29): warning CS0114: `StateMachineEvent.OnStateExit(UnityEngine.Animator, UnityEngine.AnimatorStateInfo, int)' hides inherited member `UnityEngine.StateMachineBehaviour.OnStateExit(UnityEngine.Animator, UnityEngine.AnimatorStateInfo, int)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword

This is the red error that happens only when I hit stop. Not during play mode ever, only shows up after I press stop:

 NullReferenceException: Object reference not set to an instance of an object
 AIController.OnDisable () (at Assets/Misc/AIController.cs:31)

Can anyone explain these errors in layman's terms?

Any help is appreciated, thank you.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image giraffe1 · Jan 20, 2016 at 05:26 PM 0
Share

The yellow error, I cleared by changing "public virtual void OnStateExit" to "public override void OnStateExit"

The red I am stuck.

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by JoshuaMcKenzie · Jan 20, 2016 at 06:29 PM

The warning means that your essentially redefining what "OnStateExit" is (from a method to event) since that name is already being used by the class. Your essentially overriding function with your own event. Unity isn't sure if this is what you've intended because now Unity can't properly access the old method so its issuing a warning (not an error) to let you know. While this will compile (it is a warning and valid code) I'm certain its not what you want as now the OnStateEnter and OnStateExit functions are getting overshadowed and won't get called.

also don't have your AI Controller keep track of the StateMachineBehavior. from my experience the state of these Statebehavior scripts can desync from the MonoBehavior scripts leaving your Mono script none the wiser. The reason why this doesn't work is that GetBehaviour() returned a reference in OnEnable that won't always be the "same" reference when you called it again in OnDisable().

I'm not entirely certain, but my guess is that the various sub assets that make up the animator are getting created, destroyed, and changed throughout its lifetime. So, events might not be the best way to pass info to and from the AI controller.

Instead have your StateMachineBehavior script to keep track of the AI script:

 public class AIController: MonoBehaviour
 {
     void OnEnable()
     {
         MyStateMachine[] msm = animator.GetBehaviours<MyStateMachine>();
 
         for (int i=0; i<msm.Length; i++)
         {
             msm [i].Script = this;
         }
     }


     public void RifleShotStart(){}


     public void RifleShotEnd(){}
 }

then in your StateMachince Script....

 public class MyStateMachine: StateMachineBehaviour 
 {
     public virtual MonoBehavior Script  { get;   set;  }
 
     public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         base.OnStateEnter(animator, stateInfo, layerIndex);

         if (Script != null)
             Script.RifleShotStart();
     }
 
     public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         if (Script != null)
              Script.RifleShotEnd();

         base.OnStateExit(animator, stateInfo, layerIndex);
     }
 
 }

This is the technique that I use and it has proven to be pretty solid.

Alternatively if you really don't like exposing those methods you can keep the events (but please rename them so that they aren't masking the functions!) and then have the StateMachine script remove all listeners onDisable(). Since StateMachineBehavior inherits from ScriptableObject, it also comes with OnEnable,OnDisable and OnDestroy. However, I'm a little wary of this since I'm not fully aware as to when a StateMachineBehavior will have its OnDisable called so you could end up with your events suddenly breaking.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image giraffe1 · Jan 21, 2016 at 01:57 AM 0
Share

Thanks for the response. I may have bit off more than I can chew. This is my first time using state machine behaviors, delegates and events.

The reason why this doesn't work is that GetBehaviour() returned a reference in OnEnable that won't always be the "same" reference when you called it again in OnDisable().

This line especially helped me understand the issue. I will try out you script and see what happens.

avatar image giraffe1 · Jan 21, 2016 at 02:25 AM 0
Share

After reading your response a couple times. I made some of the changes you suggested and it doesn't seem to cause any warning/errors. I know you are not a fan of this route but could you take a look at my changes? Does it look sound code wise at least? Seems to work. But my knowledge of instancing and inheritance is kind of fuzzy. I don't fully understand what is going on in the background.

$$anonymous$$y State machine script:

 using UnityEngine;
 using System.Collections;
 
 public class State$$anonymous$$achineEvent: State$$anonymous$$achineBehaviour
 {
     public delegate void StateEventHandler(Animator animator, AnimatorStateInfo stateInfo, int layerIndex);
 
     public event StateEventHandler OnStateEntered;
     public event StateEventHandler OnStateExited;
 
     override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         if (OnStateEntered != null)
         {
             OnStateEntered (animator, stateInfo, layerIndex);
         }
     }
 
     override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         if (OnStateExited != null)
         {
             OnStateExited (animator, stateInfo, layerIndex);
         }
     }
 }

And my mono script:

 using UnityEngine;
 using System.Collections;
 
 public class AIController: $$anonymous$$onoBehaviour
 {
     private Animator animator;
     private State$$anonymous$$achineEvent state$$anonymous$$achineEvent;
 
     void Awake()
     {
         animator = GetComponent<Animator>();
         state$$anonymous$$achineEvent = animator.GetBehaviour<State$$anonymous$$achineEvent>();
     }
 
     void OnEnable()
     {
         state$$anonymous$$achineEvent.OnStateEntered += RifleOneShotStart;
         state$$anonymous$$achineEvent.OnStateExited += RifleOneShotEnd;
     }
 
     public void RifleOneShotStart(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         Debug.Log("animation START");
     }
 
     public void RifleOneShotEnd(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         Debug.Log("animation END");
     }
 
     void OnDisable()
     {
         state$$anonymous$$achineEvent.OnStateEntered -= RifleOneShotStart;
         state$$anonymous$$achineEvent.OnStateExited -= RifleOneShotEnd;
     }
 }
avatar image JoshuaMcKenzie giraffe1 · Jan 21, 2016 at 03:23 AM 0
Share

That's much better, since your calling GetBehavior() only once and tracking that specific instance, you're making it easy to remove the listeners. If it works fine, then I'm all for it since the two scripts remain even more decoupled.

though if you're planning on passing stateInfo to the AI controller I've had trouble with that in my own coding. when ever I wanted to sync spawning a projectile to a specific timeframe in the animation it always flopped on me. so I kept the ti$$anonymous$$g on the statebehavior side like so. and debuffs that affected the animation speeds were stacked into my AnimationSpeeds.Attack decorator

     using UnityEngine;
     using System.Collections;
     
     public class AnimState_Attack : State$$anonymous$$achineBehaviour 
     {
         public virtual IEntityBehavior Script {get;set;}
         bool attacked = false;
     
         public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) 
         {
             if (Script == null)
                 return;
             
             animator.speed =Script.AnimationSpeeds.Attack;
     
             if (Script != null)
             {
                 float normalizedTime = (stateInfo.normalizedTime % 1);
                 if (normalizedTime < Script.AttackBehavior.AttackTime)
                 {
                     attacked = false;
                 } 
                 else if (!attacked)
                 {
                     attacked = true;
                     Script.AttackBehavior.OnAttack();
                 }
             }
         }
     }

Just a little tidbit to prepare yourself for.

avatar image giraffe1 JoshuaMcKenzie · Jan 21, 2016 at 03:54 AM 0
Share

I will definitely check out your solution. Thank you very much.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

33 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

EventManager with parameters 1 Answer

Issue subscribing to event in managed DLL 0 Answers

Trying to build system without hard coupling 2 Answers

In delegate function, add the same listener event, why the same listener be called Immediately? 0 Answers

Subscribe to an event when the application is loaded 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges