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;*/
}
}
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.
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;