- Home /
My Script Wont work?
Hi I have a script attached to the main camera, and in this script I want to choose a number between 0 to 5 . And depending on what number I get, I want a script to run. Hers my script that is attached to the main camera. I keep getting this error
NullReferenceException: Object reference not set to an instance of an object RandomFunction.Start () (at Assets/Resources/Scripts/RandomFunction.cs:22)
using UnityEngine;
using System.Collections;
public class RandomFunction : MonoBehaviour {
int n;
void Awake()
{
GetComponent<RandomFunction> ().enabled = true;
}
void Start ()
{
n=Random.Range(0,5);
if(n==0)
{
GetComponent<BlueGoUp> ().enabled = true;
}
else if(n==1)
{
GetComponent<RedGoUp> ().enabled = true;
}
else if(n==2)
{
GetComponent<GreenGoUp> ().enabled = true;
}
else if(n==3)
{
GetComponent<OrangeGoUp> ().enabled = true;
}
else if(n==4)
{
GetComponent<YellowGoUp> ().enabled = true;
}
else if(n==5)
{
GetComponent<PurpleGoUp> ().enabled = true;
}
}
}
please help.. I dont know why its doing this. The script im telling it to run, wont run.
Answer by allenallenallen · Dec 26, 2015 at 05:01 AM
First of all, this line:
GetComponent<RandomFunction> ().enabled = true;
You can't enable the script itself. If this script is disabled from the very beginning, it won't enable itself via code because it's already disabled.
The other problems are your GetComponents for other scripts. Be sure to assign them correctly.
Answer by Kimi073 · Dec 26, 2015 at 05:54 AM
You haven't defined and assigned the [...]GoUp yet.
You should define it by saying:
public GameObject GreenGoUp;
public GameObject RedGoUp;
//Others just add public GameObject before it
Then in the inspector which holds this script, assign the game object which you consider it to be GreenGoUp or RedGoUp or whatever else by dragging that game object in the hierarchy to the desire empty slot
Secondly if you want to create random number you, in this case, you should take it as
Random.Range(0,6);
in order to generate the number 5 or else it only generate random number up to 4.