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.
  2. Dismiss Notice

an object reference is required to access non-static member animation.play()

Discussion in 'Scripting' started by The-Game-Master, Aug 6, 2014.

  1. The-Game-Master

    The-Game-Master

    Joined:
    Aug 6, 2014
    Posts:
    54
    using UnityEngine;
    using System.Collections;

    public class WeaponAnimControl : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
    int RightClick = Animator.StringToHash ("RightClick");
    if(Input.GetKey ("Fire2")){
    Animator.SetBool("RightClick", true);
    Debug.Log ("Aiming Down Sights");
    }
    else{
    Animator.SetBool("RightClick", false);
    Debug.Log ("Idle-ing");
    }
    }
    }​

    Why my code isn't working is beyond me. I am new to Unity 3D, and I have some background in C and C#, but obviously not enough. What does this mean:
    Assets/WeaponAnimControl.cs(16,41): error CS0120: An object reference is required to access non-static member `UnityEngine.Animator.SetBool(string, bool)'
    Yes, my indentation is right, but it won't show on this website, even after I tried indenting again to seperate it from everything else.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    You're using the class name, so Mono is looking for a static class function. What you actually want is an instance of Animator, which you can get thusly:
    Code (csharp):
    1.  
    2. Animator anim = GetComponent<Animator>();
    3. anim.SetBool("Idle-ing", false);
    4.  
     
    The-Game-Master likes this.
  3. The-Game-Master

    The-Game-Master

    Joined:
    Aug 6, 2014
    Posts:
    54
    Thank you so much! I guess I need to keep learning if I expect to make a game.
     
  4. black1ops22

    black1ops22

    Joined:
    Mar 16, 2015
    Posts:
    3
    would it be the same for animation?
     
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    "Animation" is the class name, and it's the same way as "Animator" above.

    "animation" is essentially a shortcut for GetComponent<Animation>() - but this no longer exists in Unity 5, so it depends on which version you're using.

    Also, the Animation component is basically deprecated, and it's recommended that you use Animator for anything that doesn't depend on Animation for legacy reasons.