Update UI from script (HELP!)

I’m trying to take the name of one class to another. This is the code for the first class:

using UnityEngine;
using UnityEngine.UI;

public class Fire : MonoBehaviour 
{
    
public int MAX_MAGAZINE = 17;
    
public float damage = 10f;
    
public float range = 100f;
    
public int magazine;
    
public string nameGun = "PM-40";
   //I want take this string
public GameObject impact;
   
public Camera fps;
    
public float force = 30;



  void Start()
   
 {
        
   magazine = MAX_MAGAZINE;
    
}

and this is the second class:

using UnityEngine;
using UnityEngine.UI;

public class nomeArma : MonoBehaviour {

    private string testoRef;
    public Text text;

    void Start ()
    {
        testoRef = GetComponent<Fire>().nameGun;
        Debug.Log(testoRef);
        text.text = testoRef;
    }
   
    void Update ()
    {/*
        testoRef = GetComponent<Fire>().nameGun;
        Debug.Log(testoRef);
        text.text = testoRef;*/
    }
}

But i have this error:

and the Fire script is a component on the same object as the nomeArma script?

No, Fire script is a component of a gun and the nomeArma is the component of Text (UI)

Try this and you should know what’s the problem.

using UnityEngine.UI;

public class nomeArma : MonoBehaviour
{

    private string testoRef;
    public Text text;

    void Start()
    {
        Fire gun = GetComponent<Fire>();
        if (gun == null)
            Debug.LogError("No Fire Component found in gameobject " + gameObject.name);

        if (text == null)
            Debug.LogError("No Text Component assigned to " + gameObject.name + " " + this.ToString());

        testoRef = GetComponent<Fire>().nameGun;
        Debug.Log(testoRef);
        text.text = testoRef;
    }
}

Also name your text component e.g textLabel instead of text because word text might already be in use in C#, Unity or other libraries which would cause all sorts of problems.

public Text textLabel;

Well…you just answered your own question.

testoRef = GetComponent<Fire>().nameGun;

This says look on the gameobject this script is on and find a component called Fire, which doesn’t exist, so it can’t get it, thus creating a null error because you are trying to access nameGun from a null reference.

You need a reference to the gun somehow.

public GameObject playerGun; //drag by inspector or you'll need to assign the gun to the variable somehow

testoRef = playerGun.GetComponent<Fire>().nameGun;

Thank you! I really didn’t think about the references!