Invalid Layer Index '-1'

So, I’m rather new to Unity, and game design in general, so I’ve come across some issues, but this specific one, I haven’t been able to fix. It will not allow me to change animations when moving or jumping, and remains on the idle animation. I was hoping that I could at least understand why this error was popping up, so I can work towards fixing it. Anyways, here’s the code I used.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController2D : MonoBehaviour {
Animator animator;
Rigidbody2D rb2d;
SpriteRenderer spriteRenderer;


  
    void Start() {

    animator = GetComponent<Animator>();
    rb2d = GetComponent<Rigidbody2D>();
    spriteRenderer = GetComponent<SpriteRenderer>();

  
      
    }

 

    private void FixedUpdate()
    {
  
       if(Input.GetKey("d") || Input.GetKey("right"))
       {
            rb2d.velocity = new Vector2(2, rb2d.velocity.y);
            animator.Play("Player_Run");
       }
       else if(Input.GetKey("a") || Input.GetKey("left"))
       {
          rb2d.velocity = new Vector2(-2, rb2d.velocity.y);
       
          animator.Play("Player_Run");


       }
       else
       {
        animator.Play("Player_idle");
       }

       if(Input.GetKey("space"))
       {
            rb2d.velocity = new Vector2(rb2d.velocity.x, 3);
            animator.Play("Player_Jump");


       }
    
    }

     
}

Do you have a state in your animator called “Player_Jump”, “Player_idle”, and “Player_Run”? Double check the spelling and capitalization of these as they have to match exactly. For example should it be “Player_Idle” instead?

The naming should be the way it is. I accidentally forgot to capitalize when naming the idle animation, hence the discrepancy

Well it would help if you shared which line the error is on?

I can’t tell which line the error is on. Visual Studio is telling me everything is fine, but Unity says that ther eis an error. Whenever I click the error in Unity, it doesn’t tell me where the error is.

The error message in Unity contains a line number. What is that number? (To get the best help you should share the full error message)

Note, Visual Studio cannot tell you the location of a runtime error. It can only show you compiler errors.

Alright. So the line is 43, and heres the full error message.

Invalid Layer Index ‘-1’
UnityEngine.Animator.Play(String)
PlayerController2D:FixedUpdate() (at Assets/PlayerController2D.cs:43)

Ok yeah it definitely seems like it has something to do with your “idle” state. Can you show a screenshot of that state in your animator?

Is this the tab you’re referring to?

I don’t see underscores in the names of your states in the animator, but you are using underscores in your code. If you make them match, does it fix your problem?

Yeah, it did. I guess I was just being dumb again. Thanks for your help!

1 Like