I started with the Build a Ball tutorials, but am stuck on tutorial 7, “Displaying Score and Text”. The program runs, but the score stays at 0 when the “Player” hits the “Pick Ups”. The error that I am getting is NullReference Exception: Object reference not set to an instance of an object PlayerControl.Start() (at Assesst/Scripts/PlayerControl.cs: 21.
I check the program with the printout of the tutorial code and all of the variables. Does someone have a working game I could look at? Or if you had this problem, how did you fix it?
public Text winText; // Hello, I am null!!!
winText
is null. you need to assign it in the inspector.
Alternatively, make the code work without winText assigned.
using UnityEngine;
using UnityEngine.UI;
public class PlayerControl : MonoBehaviour
{
public float speed;
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
WarnMissingReference(countText, "Count Text");
WarnMissingReference(winText, "Win Text");
UpdateText();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVerticle = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVerticle);
rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
++count;
UpdateText();
}
}
void UpdateText()
{
bool win = count >= 8;
SetText(winText, win ? "You Win!" : "");
SetText(countText, "Count: " + count);
}
void SetText(Text obj, string text)
{
if (obj)
obj.text = text;
}
void WarnMissingReference(Object obj, string name)
{
if (!obj)
Debug.LogWarningFormat(this, "{0} has not been assigned", name);
}
}