Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Calling method from another script. Null Error.

Discussion in 'Scripting' started by Sakad, Sep 8, 2022.

  1. Sakad

    Sakad

    Joined:
    Dec 8, 2021
    Posts:
    3
    This is Method that I want to call.
    Code (CSharp):
    1. public class Canvas : MonoBehaviour
    2. {
    3.     [SerializeField] TextMeshProUGUI m_Object;
    4.     [SerializeField] TextMeshProUGUI n_Object;
    5.     int E = 10;
    6.     int P = 10;
    7.     void Start()
    8.     {
    9.        
    10.    
    11.        
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.    
    18.     }
    19.     public void LiveSetter()
    20.     {
    21.         P -= 1;
    22.         string m = P.ToString();
    23.         m_Object.text = "Your Live = "+ m ;
    24.     }
    25.     public void ELiveSetter()
    26.     {
    27.         E -= 1;
    28.         string m = E.ToString();
    29.         n_Object.text = "Enemy Live = " + m;
    30.     }
    31.    
    32. }
    and this is where I want to call
    Code (CSharp):
    1. public class EnemyBase : MonoBehaviour
    2. {
    3.     public int ELives = 10;
    4.     public Canvas canvas;
    5.     void Start()
    6.     {
    7.  
    8.     }
    9.  
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.  
    14.     }
    15.     private void OnCollisionEnter(Collision otherObj)
    16.     {
    17.         if (otherObj.gameObject.tag == "Player")
    18.         {
    19.             ELives -= 1;
    20.             canvas.ELiveSetter();
    21.            
    22.            
    23.         }
    24.     }
    25. }

    But When I want to play game I took this error. Null reference.
    upload_2022-9-8_4-8-4.png
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    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.
     
    Last edited: Sep 8, 2022
    Sakad likes this.
  3. Sakad

    Sakad

    Joined:
    Dec 8, 2021
    Posts:
    3
    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.