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
2
Question by DinostabOMG · Jun 09, 2016 at 06:45 PM · mecanimstate-machinebehaviour

StateMachineBehaviour: Where should I set up references?

When you write a normal MonoBehavior, you put references to other objects in Start(), like this:

 public class Foo : MonoBehaviour {
     RigidBody2d rb;
     
     void Start() {
         rb = GetComponentInParent<Rigidbody2D>();
     }
 }

What can I do if I want to access that parent's Rigidbody2D in a StateMachineBehavior instead?

Right now I have this:

 Rigidbody2D rb;
 
 override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
         if (rb == null) {
             rb = animator.gameObject.GetComponentInParent<Rigidbody2D>();
         }
     }

This works, but I have to wait until the state is triggered to set up the reference. And it will do the checks every time. Is there a way to do it on scene start like a MonoBehaviour does?

Originally I tried putting the same code in OnStateMachineEnter, but it was never called. I read in the docs that it won't be called for sub-state machines, but I am not using those - this machine begins running on scene play.

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by ericbegue · Jun 09, 2016 at 07:10 PM

StateMachineBehaviour inherits from ScriptableObject which has the OnEnable function. You could use this function to do the initialization.

See: https://docs.unity3d.com/ScriptReference/ScriptableObject.html

Comment
Add comment · Show 2 · 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 Deni35 · Aug 14, 2016 at 09:32 AM 1
Share

How can I access to my Animator/GameObject from OnEnable?

avatar image ZammyIsOnFire1 Deni35 · May 13, 2017 at 04:11 PM 1
Share

I think you will need to do it manually. Get all behaviors from animator and set whatever references you want.

avatar image
1

Answer by olejuer · Apr 14, 2020 at 07:12 AM

I have built a utility class that tries to solve this problem. You can inherit from this class instead of StateMachineBehaviour and you will have access to the Animator and Context properties after the state has been entered once. The Context property is a reference to a component that has to be attached to the gameObject (an exception is thrown otherwise). You can inherit from StateMachineBehaviour, if you have no custom script attached.

As for OnStateMachineEnter: this is called when you change state machines, meaning entering a sub-state machine or returning from one. It will not be called when changing states within a state machine. https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.OnStateMachineEnter.html

As for OnEnable/OnDisable, those do not give you any way to access the Animator component that is driving the state, which is somewhat annoying.

 /// <summary>
 /// A <see cref="StateMachineBehaviour"/> with a context MonoBehaviour.
 /// </summary>
 /// <typeparam name="T">Type of the context</typeparam>
 public class StateMachineBehaviour<T> : StateMachineBehaviour where T : Component
 {
     /// <summary>
     /// The context MonoBehaviour owning the state machine.
     /// </summary>
     protected T Context { get; private set; }
     
     protected Animator Animator { get; private set; }
     
     /// <summary>
     /// The transform of the owning GameObject.
     /// </summary>
     protected Transform Transform { get; private set; }
     private bool _initialized;

     public sealed override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     {
         if (!_initialized)
         {
             Animator = animator;
             Context = animator.GetComponentInParent<T>();
             if (Context == null)
                 throw new InvalidOperationException(
                     $"State machine behaviour needs sibling/parent component of type {typeof(T)}");
             Transform = Context.transform;
             _initialized = true;
             OnInitialize(animator, stateInfo, layerIndex);
         }

         OnStateEntered(animator, stateInfo, layerIndex);
     }

     /// <summary>
     /// Initialize is called when the state is entered for the first time. Called before <see cref="OnStateEntered"/>
     /// </summary>
     protected virtual void OnInitialize(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     { }

     /// <summary>
     /// Called every time the state is entered.
     /// </summary>
     protected virtual void OnStateEntered(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
     { }
 }
Comment
Add comment · 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

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

7 People are following this question.

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

Related Questions

Mecanim and script behaviour issue 1 Answer

Is there a way to get a StateMachineBehaviour on a specific State 2 Answers

Mecanim - State Behavior - Select motion clip to play at runtime 0 Answers

Where variables from StateMachineBehaviour are stored ? 0 Answers

Transition to multiple states from Entry Node in Unity 5 1 Answer


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