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

NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by SirSalt2306, May 31, 2020.

  1. SirSalt2306

    SirSalt2306

    Joined:
    May 30, 2020
    Posts:
    2
    Hi i have been trying to fix this but i have no idee what's wrong

    NullReferenceException: Object reference not set to an instance of an object
    PlayerMovement.SetAnimatorMovement (UnityEngine.Vector2 direction) (at Assets/Scripts/PlayerMovement.cs:52)
    PlayerMovement.Move () (at Assets/Scripts/PlayerMovement.cs:25)
    PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:19)



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

    public class PlayerMovement : MonoBehaviour {

    public float speed;
    private Vector2 direction;
    private Animator animator;

    void start()
    {
    animator = GetComponent<Animator>();
    }

    void Update()
    {
    TakeInput();
    Move();
    }

    private void Move()
    {
    transform.Translate(direction * speed * Time.deltaTime);
    SetAnimatorMovement(direction);
    }

    private void TakeInput()
    {
    direction = Vector2.zero;

    if(Input.GetKey(KeyCode.W))
    {
    direction += Vector2.up;
    }
    if (Input.GetKey(KeyCode.A))
    {
    direction += Vector2.left;
    }
    if (Input.GetKey(KeyCode.S))
    {
    direction += Vector2.down;
    }
    if (Input.GetKey(KeyCode.D))
    {
    direction += Vector2.right;
    }
    }

    private void SetAnimatorMovement(Vector2 direction)
    {
    animator.SetFloat("xDir", direction.x);
    animator.SetFloat("yDir", direction.y);
    }

    }



    please help
     

    Attached Files:

  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    Use code tags...

    Otherwise, the error message points to SetAnimatorMovement. And since animator is the likely culprit, that is probably null.

    The reason it is null is because your Start is lowercase. start vs Start isn't the same.
     
    SirSalt2306 and Yoreki like this.
  3. SirSalt2306

    SirSalt2306

    Joined:
    May 30, 2020
    Posts:
    2
    Thank you so much. I only started yesterday so i still don’t know anything.