I try to finish the “Ruby’s Adventure: 2D Beginner”, and when I want to finish “Sprite Animation”, there are some errors. I just copy the code from the tutorial and I tried many times but totally don’t know how to fix it.
The error is:
NullReferenceException: Object reference not set to an instance of an object
Rubycontroller.Update () (at Assets/Script/Rubycontroller.cs:48)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rubycontroller : MonoBehaviour
{
public float speed = 3.0f;
public int maxHealth = 5;
public float timeInvincible = 2.0f;
public int health { get { return currentHealth; } }
int currentHealth;
bool isInvincible;
float invincibleTimer;
Rigidbody2D rigidbody2d;
Animator animator;
Vector2 lookDirection = new Vector2(0, -1);
// Start is called before the first frame update
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
currentHealth = 4;
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
//Vector2 position = rigidbody2d.position;
//position.x = position.x + speed * horizontal * Time.deltaTime;
//position.y = position.y + speed * vertical * Time.deltaTime;
Vector2 move = new Vector2(horizontal, vertical);
if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
{
lookDirection.Set(horizontal, vertical);
lookDirection.Normalize();
}
animator.SetFloat("Speed", move.magnitude);
animator.SetFloat("Look X", lookDirection.x);
animator.SetFloat("Look Y", lookDirection.y);
Vector2 position = rigidbody2d.position;
position = position + move * speed * Time.deltaTime;
rigidbody2d.MovePosition(position);
if (isInvincible)
{
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
isInvincible = false;
}
}
public void ChangeHealth(int amount)
{
if (amount < 0)
{
animator.SetTrigger("Hit");
if (isInvincible)
return;
isInvincible = true;
invincibleTimer = timeInvincible;
}
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
Debug.Log(currentHealth + "/" + maxHealth);
}
}