I’m going through the book “Learning C# by developing games with unity 3d” and I’m at the point of referencing other scripts/components (chapter 6; creating two GameObjects and a new script). I may not use the correct terminology as I am very new to everything, so If something is wrong with the words I use, please correct me.
In this lesson, I create a capsule and a cube. Attach a script to them which has two methods, SpinLeft and SpinRight, which do what they’re called.
Then I have another script which finds the two GameObjects. Calls/references the two methods which are SpinLeft and Right. And binds them to the arrow keys to spin the cube and capsule left or right depending on the arrow key.
Looking through the code and reading over the lesson, I understand how it works but when I hit the play button in unity, I receive a NullReferenceException and I don’t understand why (The specific message will be at the bottom of the page). Can anyone help me with this?
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);
}
}
using UnityEngine;
using System.Collections.Generic;
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();
}
}
}
NullReferenceException: Object reference not set to an instance of an object
LearningScript.Update () (at Assets/Code/Scripts/LearningScript.cs:31)
NullReferenceException: Object reference not set to an instance of an object
LearningScript.Update () (at Assets/Code/Scripts/LearningScript.cs:36)
NullReferenceException
UnityEngine.GameObject.GetComponent[Spinner] () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/UnityEngineGameObject.cs:28)
LearningScript.Update () (at Assets/Code/Scripts/LearningScript.cs:26)
NullReferenceException
UnityEngine.GameObject.GetComponent[Spinner] () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/UnityEngineGameObject.cs:28)
LearningScript.Update () (at Assets/Code/Scripts/LearningScript.cs:21)
These are the only console messages. The debug.log is not working.