I keep getting a “NullReferenceException: Object reference not set to an instance of an object” when I run this script, and I am pulling my hair out here, I can’t figure out why this is being thrown at me… maybe one of you guys can see what I missed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class setRandom : MonoBehaviour {
private Text inputWeight;
//private Text inputHeight;
//private Text inputRace;
//private Text inputClass;
// Use this for initialization
void Start () {
inputWeight = GetComponent<Text> ();
//inputHeight = GetComponent<GUIText> ();
//inputRace = GetComponent<GUIText>();
//inputClass = GetComponent<GUIText> ();
switch (Random.Range (0, 4)) {
case 0:
inputWeight.text = "Lean";
break;
case 1:
inputWeight.text = "Athletic";
break;
case 2:
inputWeight.text = "Muscular";
break;
case 3:
inputWeight.text = "Heavyset";
break;
}
}
// Update is called once per frame
void Update () {
}
}
According to Unity, its breaking on either line 29 or 32.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class setRandom : MonoBehaviour {
private Text input_Weight;
//private Text inputHeight;
//private Text inputRace;
//private Text inputClass;
// Use this for initialization
void Start () {
input_Weight = GetComponent<Text> ();
//inputHeight = GetComponent<GUIText> ();
//inputRace = GetComponent<GUIText>();
//inputClass = GetComponent<GUIText> ();
switch (Random.Range (0, 3)) {
case 0:
input_Weight.text = "Lean";
break;
case 1:
input_Weight.text = "Athletic";
break;
case 2:
input_Weight.text = "Muscular";
break;
case 3:
input_Weight.text = "Heavyset";
break;
}
}
// Update is called once per frame
void Update () {
}
}
I can offer another option. Set the ‘Text’ to public and drag the proper textfield to it in the inspector. Please note, that this is not more/less correct, but I only point this out so you can know of the option & that it might help you fix/track down what’s wrong currently.
One other note: Your random range will never give you ‘3’. For integers (whole numbers), the upper bound is exclusive, so if you want [0, 1, 2, 3], use Random.Range(0,4)