Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Calling Objects from StateMachineBehaviour

Discussion in 'Animation' started by Nightmarer666, Sep 2, 2022.

  1. Nightmarer666

    Nightmarer666

    Joined:
    Feb 14, 2021
    Posts:
    9
    Hello all.

    I'm not able to make this script work in a State Machine. I want to make unactive one layer and I want to change one animator parameter. The problem is that whis script is not compiling. Any clue about how can this be done?

    Code (CSharp):
    1. public class SnorHelmetRemove : StateMachineBehaviour
    2. {
    3.    protected GameObject headParent;
    4.    protected Animator animator;
    5.    protected bool checkHelmet;
    6.  
    7.    private void OnEnable() {
    8.        animator = GameObject.GetComponent<Animator>();
    9.        bool checkHelmet = animator.GetBool("IsWearingHelmet");
    10.        headParent = GameObject.Find("HeadParent");
    11.    }
    12.  
    13.    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    14.    {
    15.  
    16.        Debug.Log("Helmet is " + checkHelmet);
    17.        headParent.SetActive(false);
    18.    }
    19.  
    20.    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    21.    {
    22.        if (checkHelmet) {
    23.            Debug.Log("Helmet is " + checkHelmet);
    24.            animator.SetBool("IsWearingHelmet",false);
    25.        }   else {
    26.            Debug.Log("Helmet is " + checkHelmet);
    27.            animator.SetBool("IsWearingHelmet",true);
    28.        }
    29.    }
    30. }
    The error I am receiving while trying to compile is in this line animator = GameObject.GetComponent<Animator>(); And the error message is this one:

    An object reference is requiered for the non-static field, method or property GameObject.GetComponent();

    I have followed the Unity guide https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Animator.GetBool.html and the getObject class is in lower case, but it still don't work if I change this, and I have this error:

    The name 'gameObject' doesn't exists in the current context

    Can anybody help me?
     
    Last edited: Sep 2, 2022