This show this error: NullReferenceException: Object reference not set to an instance of an object
Spikes.Start () (at Assets/Spikes.cs:12)
The scripts are:
Spike script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spikes : MonoBehaviour
{
private PlayerController2D player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController2D>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
player.Damage(1);
}
}
}
PlayerController2D script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerController2D : MonoBehaviour
{
Animator animator;
Rigidbody2D rb2d;
SpriteRenderer SpriteRenderer;
bool isGrounded;
[SerializeField]
Transform groundCheck;
[SerializeField]
Transform groundCheckL;
[SerializeField]
Transform groundCheckR;
[SerializeField]
private float walkSpeed = 1.5f;
[SerializeField]
private float jumpSpeed = 5f;
//Stats
public int curHealth;
public int maxHealth = 100;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
SpriteRenderer = GetComponent<SpriteRenderer>();
curHealth = maxHealth;
}
private void Update()
{
if(curHealth > maxHealth)
{
curHealth = maxHealth;
}
if(curHealth <= 0)
{
Die();
}
}
private void FixedUpdate()
{
if((Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"))) ||
(Physics2D.Linecast(transform.position, groundCheckL.position, 1 << LayerMask.NameToLayer("Ground"))) ||
(Physics2D.Linecast(transform.position, groundCheckR.position, 1 << LayerMask.NameToLayer("Ground"))))
{
isGrounded = true;
}
else
{
isGrounded = false;
animator.Play("Player_jump");
}
if(Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(walkSpeed, rb2d.velocity.y);
if(isGrounded)
animator.Play("Player_walk");
SpriteRenderer.flipX = false;
}
else if(Input.GetKey("a") || Input.GetKey("left"))
{
rb2d.velocity = new Vector2(-walkSpeed, rb2d.velocity.y);
if (isGrounded)
animator.Play("Player_walk");
SpriteRenderer.flipX = true;
}
else
{
if (isGrounded)
animator.Play("Player_idle");
rb2d.velocity = new Vector2(0, rb2d.velocity.y);
}
if(Input.GetKey("space") && isGrounded)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpSpeed);
animator.Play("Player_jump");
}
}
void Die()
{
//Restart
SceneManager.LoadScene(SceneManager.GetActiveScene ().buildIndex);
}
public void Damage(int dmg)
{
curHealth -= dmg;
}
}
HUD Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD : MonoBehaviour
{
public Sprite[] HeartSprites;
public Image HeartUI;
public PlayerController2D player;
void Start()
{
}
void Update()
{
HeartUI.sprite = HeartSprites[player.curHealth];
}
}