P
P
pmozil2018-10-18 01:54:18
C++ / C#
pmozil, 2018-10-18 01:54:18

Error in Unity3D NullReferenceException: Object reference not set to an instance of an object. Why?

I'm making a simple game. When a player collects boxes, the text object is updated, which shows the number of collected boxes. But I get an error NullReferenceException: Object reference not set to an instance of an object and the text is not updated.
Please help, I've already spent half a day and I can't find the error.
CounterController class

public class CounterController : MonoBehaviour {
  int numberOfBoxes;
  Text counterView;
  // Use this for initialization
  void Start () {
    ResetCounter ();
    
  }
  public void IncrementCounter(){
    numberOfBoxes++;
    counterView.text = numberOfBoxes.ToString();
  }

  public void ResetCounter(){
    numberOfBoxes=0;
    counterView.text = numberOfBoxes.ToString();
  }


}

PickUpBox class
public class PickUpBox : MonoBehaviour {
  CounterController counterController;
  
  void Start () 
      {
    counterController = GameObject.Find ("Manager").GetComponent<CounterController> ();
    if (counterController == null) 
    {
      Debug.LogError ("CounterController не найден.");
    }
  }
  
  void OnTriggerEnter2D (Collider2D other) 
  {
    if (other.gameObject.name == "Girl")
    {
      Destroy (this.gameObject);
      counterController.IncrementCounter ();

    }

  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2018-10-18
@freeExec

Should be And in the inspector you need to drag the element with the Text component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question