- Home /
NullReferenceException?
I've got a very simple script from a tutorial, but when I try to run it, it gives the NullReferenceException error in the console everytime I press one of the arrow keys.
Anyone that knows what might be wrong with my code?
Learningscript.cs: using UnityEngine; using System.Collections;
public class LearningScript : MonoBehaviour
{
GameObject capsuleGO;
Spinner cubeComp;
void start()
{
capsuleGO = GameObject.Find ("Capsule");
Debug.Log (capsuleGO);
cubeComp = GameObject.Find ("Cube").GetComponent<Spinner>();
Debug.Log(cubeComp);
}
void Update()
{
if (Input.GetKey (KeyCode.LeftArrow))
{
capsuleGO.GetComponent<Spinner> ().SpinLeft();
}
if(Input.GetKey (KeyCode.RightArrow))
{
capsuleGO.GetComponent<Spinner>().SpinRight();
}
if(Input.GetKey (KeyCode.UpArrow))
{
cubeComp.SpinLeft();
}
if(Input.GetKey (KeyCode.DownArrow))
{
cubeComp.SpinRight();
}
}
}
spinner.cs:
using UnityEngine;
using System.Collections;
public class Spinner : MonoBehaviour {
public void SpinLeft()
{
transform.Rotate (0, 0, 60 * Time.deltaTime);
}
public void SpinRight()
{
transform.Rotate(0, 0, -60 * Time.deltaTime);
}
}
Answer by rutter · Jan 02, 2014 at 11:45 PM
I'll assume you understand what a NullReferenceException is. It's fine if you don't. Google might help, or just ask in a comment here.
So, you have two references: capsuleGO
and cubeComp
. Both are populated by a combination of GameObject.Find()
and GetComponent()
.
If there is no GameObject named "Capsule",
capsuleGO
will be nullIf there is no GameObject named "Cube", you'll get a null reference exception at start
If "Cube" exists but has no
Spinner
component attached,cubeComp
will be null
Finally, C# is case-sensitive: start
and Start
are not the same name. Unity is looking for a function named Start
.
Thanks! I triple checked the code the tutorial had written out, can't believe I missed that haha
Answer by mohamedk2014 · Jun 11, 2019 at 04:06 PM
i have this problem this is: use capital letter in "cube" and "capsule" because the name of the game object in unity for those items begin with capital letter
Your answer
Follow this Question
Related Questions
troubleshooting NullReferenceException 2 Answers
NullReferenceException 2 Answers
Material[] Object reference not set when instantiating 2 Answers
NullReference Exception when adding a class 2 Answers
array initialisation c# 1 Answer