Search code examples
unity-game-enginecrashtooltip

Why does unity crash when using tooltips?


I coded a tooltip by following a tutorial on youtube. At first it worked and now it doesnt. I dont know the reason why it crashed but there was 2 errors saying "NullReferenceException: Object reference not set to an instance of an object.

" 2 scripts: "ToolTip" and "ToolTipManager" ToolTip's code:

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

public class ToolTip : MonoBehaviour
{

    public string message;

    private void OnMouseEnter()
    {
        ToolTipManager._instance.SetAndShowToolTip(message);
    }

    private void OnMouseExit()
    {
        ToolTipManager._instance.HideToolTip();
    }
}

ToolTipManager's code:

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

public class ToolTipManager : MonoBehaviour
{

    public Camera cam;

    public static ToolTipManager _instance;

    public TextMeshProUGUI textComponent;

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }

    void Start()
    {
        Cursor.visible = true;
        gameObject.SetActive(false);
    }

    void Update()
    {
        transform.position = new Vector2(cam.ScreenToWorldPoint(Input.mousePosition).x, cam.ScreenToWorldPoint(Input.mousePosition).y);
    }

    public void SetAndShowToolTip(string message)
    {
        gameObject.SetActive(true);
        textComponent.text = message;
    }

    public void HideToolTip()
    {
        gameObject.SetActive(false);
        textComponent.text = string.Empty;
    }
}

I don't know what's causing it.


Solution

  • Doesn't crash anymore so marking as solve.