NullReferenceException throws what to do?

There are two classes:
public class SpawnBox : MonoBehaviour {
 public Object obj;
 public GameObject gObj;
 public float min;
 public float max;
 private float inq;
 int turn;

 void Start()
{

}


 void Update () {

}

 public void Spawn()
{
 gObj.transform.position = new Vector3(Random.Range(-12.9 f, 12.9 f), Random.Range(21.0 f, 51.0 f), 0);
 Instantiate(obj, gObj.transform.position, Quaternion.identity);
}
}


public class Rand : MonoBehaviour {
 int dawn;

 void Start () { 
 } 
 void Update () {
if(Input.GetKey(KeyCode.Q))
{
 dawn = Random.Range(0, 10);
 if(dawn == 3)
{
GetComponent<spawnbox>().Spawn();
}
else
{
print(dawn);
 } 
}
}
}</spawnbox>


Throws NullReferenceException in line: "GetComponent().Spawn();
"
I tried to create an instance of the class, the same thing =(
July 2nd 19 at 14:24
1 answer
July 2nd 19 at 14:26
Solution
GetComponent() finds the component.
Do you understand what you're looking for a component/script on the same object on which hung the script Rand ?

if he is not on the same subject, and the child or just in the scene, or try to organize or search through the GameObject.FindObjectOfType()
And if I don't use GetComponent, but instead will create a class variable or make this method static, it will search the class into the object, which weighs class Rand?
PS Try using GameObject.FindObjectOfType(), thanks - Matteo65 commented on July 2nd 19 at 14:29
Still read you a certificate stating how does GetComponent(). There is in English but still must be understandable.

To create a public class Rand object reference SpawnBox :
public SpawnBox spawnBox1; // or something similar)
and in the editor in the scene to explicitly indicate Yes so that's just done more or less correctly.

Static method - of course it is possible and so. but it's not quite the same, not component approach) suddenly you several different there should be generators of objects, differing only in some parameter.

In such matters - I would advise all the same as the examples for unity to see about arsitektur applications to read the simple courses. - earline.Fad commented on July 2nd 19 at 14:32
and let me remind you that here is the answer (and if helped) to note the response that hung unanswered)) - earline.Fad commented on July 2nd 19 at 14:35
I understand why I have to create the class object not working:
"To create a public class Rand object reference SpawnBox :
public SpawnBox spawnBox1; // or something similar)
and in the editor in the scene to explicitly specify"
I forgot to explicitly specify on stage.
Thank you. - Matteo65 commented on July 2nd 19 at 14:38

Find more questions by tags Unity Game Engine