Calling method from another script. Null Error.

This is Method that I want to call.

public class Canvas : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI m_Object;
    [SerializeField] TextMeshProUGUI n_Object;
    int E = 10;
    int P = 10;
    void Start()
    {
       
    
       
    }

    // Update is called once per frame
    void Update()
    {
   
    }
    public void LiveSetter()
    {
        P -= 1;
        string m = P.ToString();
        m_Object.text = "Your Live = "+ m ;
    }
    public void ELiveSetter()
    {
        E -= 1;
        string m = E.ToString();
        n_Object.text = "Enemy Live = " + m;
    }
   
}

and this is where I want to call

public class EnemyBase : MonoBehaviour
{
    public int ELives = 10;
    public Canvas canvas;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnCollisionEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
        {
            ELives -= 1;
            canvas.ELiveSetter();
           
           
        }
    }
}

But When I want to play game I took this error. Null reference.

Gonna guess you haven’t assigned the canvas in the inspector in your Enemy base script.

Edit: Also, you shouldn’t name your scripts the same name as Unity classes. Canvas is also a class in UnityEngine.UI namespace, and naming your own script the same thing is going to cause you a world of headache.

1 Like

Thank You so much. I was trying to find solution for 4 hours. I didn’t know this necessity. It solved my problem. and Thanks for your advice. I will be more carefull.