Animator.SetBool doesn't work

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

public class PlayerMovement : MonoBehaviour
{
    Animator anim;

    public CharacterController2D control;

    public float runSpeed = 40f;

    float horizontalMove = 0f;

    bool IsJumping = false;

    // Update is called once per frame
    void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
        if (Input.GetButtonDown("Jump") || Input.GetAxisRaw("Vertical") > 0.6)
        {
            IsJumping = true;
        }

        if (Input.GetAxisRaw("Horizontal") != 0)
        {
            anim.SetBool("IsRunning", true);
        }

    }

    private void FixedUpdate()
    {
        //movement
        control.Move(horizontalMove * Time.fixedDeltaTime, false, IsJumping);
        IsJumping = false;

    }
}

this is the code

when I enter in the if console show me this error:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/scripts/PlayerMovement.cs:29)

PLS HELP

Did you set anim?

You need to get the reference to your animator.

Start()
{
   anim = GetComponent<Animator>();
}

If you add that to Start() your code should work, provided the Animator is attached to the same GameObject that your script is attached to.

If your animator is in a child object, use GetComponentInChildren() or if it’s in the parent object use GetComponentInParent().

ty dude

1 Like