D
D
Deathgar2016-11-23 16:54:20
Unity
Deathgar, 2016-11-23 16:54:20

NullReferenceException gives 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.9f, 12.9f), Random.Range(21.0f, 51.0f), 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);
            }                
        }
  }
}

Throws a NullReferenceException on the line with: "GetComponent().Spawn();
"
I tried instantiating the class, same =(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2016-11-23
@Deathgar

GetComponent() does not find the component.
Do you understand that you are looking for a component/script on the same object where the Rand script is hung?
if it's not on the same object, but on a child or just in the scene, try to either organize it correctly or search through GameObject.FindObjectOfType()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question