0

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();
    }
}

Screenshot. enter image description here

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.

Malcolm
  • 784
  • 3
  • 7
  • 20
  • You probably want to check other and gameObject before visit them, like this: if (other != null && other.gameObject != null && other.gameObject.CompareTag("Gold")) – Jimmy liu Jun 29 '20 at 04:23
  • Thank you Jimmy liu, I never though of that. However I managed to get it working by changing void start() to void Awake() in ScoreManager.cs – Malcolm Jun 29 '20 at 23:32
  • Oh I see, that's because of there is a chance "other"s might not be created yet in Awake(). Never mind, my code won't work anyway in that case. it only prevents error logging. :) – Jimmy liu Jun 30 '20 at 03:43
  • Ah! ok, thanks anyway Jimmy liu. – Malcolm Jul 01 '20 at 15:24

0 Answers0