- Home /
NullReferenceException when I click a button c#
I am following a tutorial to learn how to use unity to make an RPG because I'm new to development with this engine. I followed the tutorial exactly word for word in code, but I get a NullReferenceException on this certain line in it, while the person who is doing the tutorial doesn't. He is using an older version of Unity, so do I need to update something in my MonoDevelopment code?
This is the code:
using UnityEngine;
using System.Collections;
public class GameSettings : MonoBehaviour {
void Awake() {
DontDestroyOnLoad(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SaveCharacterData() {
GameObject pcNew = GameObject.Find("pc");
PlayerCharacter pcClass = pcNew.GetComponent<PlayerCharacter>();
PlayerPrefs.SetString("Player Name", pcClass.Name);
}
public void LoadCharacterData() {
}
}
Where is the error showing up? The console tells you the line.
Already, are you sure "pc" should not be "Pc"?
Answer by EHogger · Aug 02, 2013 at 09:47 PM
I'll assume that the null error is coming from the GameObject.Find
line. Check that you actually have a game object named "pc".
... a game object is ... an object in the game. It can't be in a file.
This script is looking for an active game object in your scene called "pc". It's then looking for a script on that object called PlayerCharacter.
One or both of those things is missing. If you look at the error message it will tell you which of these lines is causing the problem.
I know it's an object in a game. This is the pc GameObject code
GameObject pc = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity) as GameObject;
pc.name = "Hero";
So when I start the program, the code creates a GameObject called Hero
And that solves it. I changed GameObject.Find("pc") to GameObject.Find("Hero") and that fixed it right up! Thanks for making me look at that code piece again :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException error in an array of objects 0 Answers
Can't find source of trigger Null Reference Exception 1 Answer