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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Enemy Run Animation

Discussion in 'Scripting' started by SMGreer, Mar 17, 2015.

  1. SMGreer

    SMGreer

    Joined:
    Dec 13, 2014
    Posts:
    14
    So basically I'm trying to have it so that when my enemy moves, the run animation plays.

    However, everything I've tried so far just won't work. My code is currently this:

    Code (CSharp):
    1. if (Rigidbody2D.velocity > 0.01)
    2.         {
    3.             animator.SetInteger ("Speed", 0);
    4.         }
    5.  
    6.         if (Rigidbody2D.velocity < 0.01)
    7.         {
    8.             animator.SetInteger ("Speed", 1);
    9.         }
    Obviously though, for that I get the error:

    "An object reference is required to access non-static member `UnityEngine.Rigidbody2D.velocity'"

    I've been trying to figure out an alternative to acknowledge a change in velocity/movement but so far haven't succeeded. Any help in finding a solution would be greatly appreciated.
     
  2. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Last edited: Mar 17, 2015
  3. Roderyk

    Roderyk

    Joined:
    Mar 5, 2015
    Posts:
    75
    This should work

    Code (CSharp):
    1. private RigidBody2D rb;
    2. private Animator animator;
    3.  
    4. void Awake()
    5. {
    6.     rb = GetComponent<RigidBody2D>();
    7.     animator = GetComponent<Animator>();
    8. }
    9.  
    10. void Update()
    11. {
    12.     animator.SetInteger("Speed", rb.velocity != Vector2.zero ? 1 : 0);
    13. }
     
  4. SMGreer

    SMGreer

    Joined:
    Dec 13, 2014
    Posts:
    14
    Thanks to both of you, big help! Finally got it working and can move on to the next bit.

    Again, thank you very much! Hopefully one day I can be as helpful to the community as you both.