I am quite new to unity and have search everywhere but can't seen to find a solution to my problem.
I keep getting the following error In my Coin.cs class whenever the player collides with a coin.
NullReferenceException: Object reference not set to an instance of an object Coin.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Coin.cs:13)
Coin.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
public int coinValue = 1;
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
ScoreManager.instance.ChangeScore(coinValue);
}
}
}
ScoreManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager instance;
public TextMeshProUGUI text;
int score;
void start()
{
if(instance == null)
{
instance = this;
}
}
public void ChangeScore(int coinValue)
{
Debug.Log("Coin value. " + coinValue);
score += coinValue;
text.text = "X0" + score.ToString();
}
}
I also have to following in my PlayerController class.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Gold"))
{
Destroy(other.gameObject);
GameSounds.clip = CoinSound;
GameSounds.Play();
}
}
Any help would be greatly appreciated.