R
R
Roman Alim2020-05-06 14:03:10
Unity
Roman Alim, 2020-05-06 14:03:10

Unity NullReferenceException: Object reference not set to an instance of an object how to overcome?

Good day, I decided to start working with Unity over the weekend. Knowledge of C# is relatively low. To begin with, I decided to make a 2D platformer, it seems that this is the easiest.

the code

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

public class player_controls : MonoBehaviour
{
    Rigidbody2D rb;
    Animator anim;
    public float speed = 6f;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            jump();
        }

        if (Input.GetAxis("Horizontal") == 0)
        {
            anim.SetInteger("animation", 1);
        } 
        else
        {
            FlipHero();
            anim.SetInteger("animation", 2);
        }
    }

    
    void FlipHero()
    {
        if (Input.GetAxis("Horizontal") < 0)
        {
            transform.localRotation = Quaternion.Euler(0, 180, 0);
        } else
        {
            transform.localRotation = Quaternion.Euler(0, 0, 0);
        }
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
    }
    void jump()
    {   
        rb.AddForce(transform.up * 12f, ForceMode2D.Impulse);
    }
}


And the error itself: NullReferenceException: Object reference not set to an instance of an object
player_controls.Update () (at Assets/scripts/player_controls.cs:25)

Google, Google and similar questions looked, did not help much.

It's just that the animation does not work ... How to be, please describe in an accessible language.)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
2
2CHEVSKII, 2020-05-06
@Eroliy

Not so Googled and not looked there. Your anim is not assigned.

G
GavriKos, 2020-05-06
@GavriKos

C# knowledge is relatively low

OK, in an accessible language - learn seasharp first. The error has little to do with the unit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question