C# GameObject Reference throws NullReferenceException

Recommended Posts

I'm doing a test quest.

The player gets a quest from an NPC to bring him fish.

Once the player picks up the fish, the original NPC gets replaced by a new one with a new conversation trigger. The NPC tells the Player "Well done" and should give 200xp.

The script tells the xp counter to go up by making a reference to the gameobject that holds the text component

But it throws this error:

I'm aware that the error may hide in plain sight. I just have to sort this out, since I'm writing the AI at the same time, and the time it takes to resolve everyone of these errors is tremendous.

Plus, I think I'll learn something. I've been having trouble with some basic functionalities recently. There might be something wrong with my understanding on how programming works.

Glad if someone could help (:

Edit: I'm fully aware that the update function requires an input. I call the function in the editor when the dialogue ends, it still doesn't work.

Edited by Felis Nigripes

Share on other sites

It looks like your GameObject.FInd ("XPCounter") returns null. Maybe it's the wrong name (spelling error), maybe what you're looking for isn't a GameObject (I seem to remember UI things being different somehow, but it's been too long since I looked at Unity stuff to be sure).

Share on other sites
Just now, Lactose said:

It looks like your GameObject.FInd ("XPCounter") returns null. Maybe it's the wrong name (spelling error), maybe what you're looking for isn't a GameObject (I seem to remember UI things being different somehow, but it's been too long since I looked at Unity stuff to be sure).

The spelling is correct. I checked a dozen times. And I made the XPCounter a gameobject on purpose. Before that it was a UI, and I suspected I wouldn't be able to access that by a gameobject reference.

Maybe referencing a UI would help?

Share on other sites

Add a debug line after Find -- if TextHolder == null Debug.Log("Find failed") to see whether or not that's where the problem is. If might not solve the issue, but at least helps narrow down where the problem is.

Share on other sites

TextHolder is the only thing that can be null on that line.  The GameObject wasn't found.

"This function only returns active GameObjects." -- Documentation

Make sure the game object is in the scene (not the project) and it's active.

You should also make sure there aren't any "invisible" parts of the game object's name, such as leading or trailing spaces.

Eventually, you should think about avoiding searching for objects by name, and directly reference them by setting up those references in the scenes, prefabs, and prefab instantiation scripts.  This will increase the program's maintainability and efficiency.

Edited by Nypyren

Share on other sites

Or a space between "XP" and "Counter", as in "XP Counter".

It's always a good idea to check for null whenever you use a function that can return a null value, such as GameObject.Find or MonoBehaviour.GetComponentInChildren. It's part of an approach called defensive programming, and it can help avoid a lot of hard-to-find bugs.

As a side note, since you're using the Dialogue System, there might be an easier way to implement the quest than replacing the entire NPC. When the player picks up a fish, you can set a Dialogue System variable. For example, in a C# script:

DialogueLua.SetVariable("HasFish", true);

Use a single conversation on the NPC, but branch the conversation based on the value of the variable. If HasFish is false, follow one branch of the conversation. If HasFish is true, follow the other branch.

Share on other sites

I sort of figured it out:

@NypyrenYou were right, the script can't access the textholder if it's deactivated, even if I assign it in the editor.

Since I have my text inside the quest menu, which is deactivated by default, it can not be accessed at all.

Kinda sucks

I could of course just put the xp counter on screen at all time, but then I wouldn't have my neat little menu where all the information is stored.

Haven't decided yet wether to just roll with it or find some clumsy workaround. Any ideas?

Edited by Felis Nigripes

Share on other sites

Option 1:  Assign the reference in the inspector:

Check this tutorial out where he makes a public GameObject field in his C# code, and then in the inspector, drags an object into the slot.

The first 2-6 minutes or so should demonstrate what I mean.  This kind of reference will work even if the GameObject is inactive.

Basically, if you follow the same steps, you would make your TextHolder public, edit the scene or prefab(s) so that the TextHolder reference is assigned in the scene or prefab instead of using GameObject.Find at all.  When the scene or prefab is loaded, Unity will automatically assign the variable to the one you drag-and-dropped in the editor.

Option 2 is:  If you instantiate a prefab by using AssetBundle.LoadAsset, AssetDatabase.LoadAsset, Resources.Load, etc. followed by Object.Instantiate, immediately after you instantiate it, you can assign its public member variables.  If your program is well-designed, the point at which you instantiate a prefab will be a point at which you already have the references available that you want to assign to those fields.

Unfortunately, Unity does not yet let us initialize things using C# constructors.  That would be Option 3, if it becomes available in the future.

Edited by Nypyren

Share on other sites

I got it!

Not sure how though. I tried a public gameobject before and it didn't work.

Perhabs it's because I never removed the private reference line in the start function. Maybe this blocked out the public reference, thus creating the error. Weirdly enough I put it back in for tests sake and it still worked.

It's mysterious to me, but it's working now. Thanks for the help.

Just now, Tony Li said:

Or a space between "XP" and "Counter", as in "XP Counter".

It's always a good idea to check for null whenever you use a function that can return a null value, such as GameObject.Find or MonoBehaviour.GetComponentInChildren. It's part of an approach called defensive programming, and it can help avoid a lot of hard-to-find bugs.

As a side note, since you're using the Dialogue System, there might be an easier way to implement the quest than replacing the entire NPC. When the player picks up a fish, you can set a Dialogue System variable. For example, in a C# script:


DialogueLua.SetVariable("HasFish", true);

Use a single conversation on the NPC, but branch the conversation based on the value of the variable. If HasFish is false, follow one branch of the conversation. If HasFish is true, follow the other branch.

I will definitely try this out, thanks.

Create an account

Register a new account

• 11
• 16
• 11
• 13
• 11
• Similar Content

• Hi everyone! I've developed a game called The Last Dog (ZOMBIES + DOGS) and was wondering if you could give it a try in order for me to analyse your behaviour in analytics. Give it a shot! Please download it here: https://florsyl.wixsite.com/thelastdog2 and let me know if you detect any bugs. VIDEO.3gp

• Hello fellow devs!
Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

In Pseudo-Code:
angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
index = (int) (angle / (PI / 5));
PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

I can't get my head around it. Any suggestions? Is the whole approach doomed?

Thank you in advance for any input!

• Hello Everyone! My name is HyprStorm and I am looking for experience with pixel art. If you need a pixel artist for a side project or a small game, then I am your guy! (Hopefully...) I would like to work on pixel art for a small project. I don’t need any money or anything, all I’d like is to be stated as one of the Artists. I’m looking for experience in the field. PM me .

• By devbyskc
Hi Everyone,
Like most here, I'm a newbie but have been dabbling with game development for a few years. I am currently working full-time overseas and learning the craft in my spare time. It's been a long but highly rewarding adventure. Much of my time has been spent working through tutorials. In all of them, as well as my own attempts at development, I used the audio files supplied by the tutorial author, or obtained from one of the numerous sites online. I am working solo, and will be for a while, so I don't want to get too wrapped up with any one skill set. Regarding audio, the files I've found and used are good for what I was doing at the time. However I would now like to try my hand at customizing the audio more. My game engine of choice is Unity and it has an audio mixer built in that I have experimented with following their tutorials. I have obtained a great book called Game Audio Development with Unity 5.x that I am working through. Half way through the book it introduces using FMOD to supplement the Unity Audio Mixer. Later in the book, the author introduces Reaper (a very popular DAW) as an external program to compose and mix music to be integrated with Unity. I did some research on DAWs and quickly became overwhelmed. Much of what I found was geared toward professional sound engineers and sound designers. I am in no way trying or even thinking about getting to that level. All I want to be able to do is take a music file, and tweak it some to get the sound I want for my game. I've played with Audacity as well, but it didn't seem to fit the bill. So that is why I am looking at a better quality DAW. Since being solo, I am also under a budget contraint. So of all the DAW software out there, I am considering Reaper or Presonus Studio One due to their pricing. My question is, is investing the time to learn about using a DAW to tweak a sound file worth it? Are there any solo developers currently using a DAW as part of their overall workflow? If so, which one? I've also come across Fabric which is a Unity plug-in that enhances the built-in audio mixer. Would that be a better alternative?
I know this is long, and maybe I haven't communicated well in trying to be brief. But any advice from the gurus/vets would be greatly appreciated. I've leaned so much and had a lot of fun in the process. BTW, I am also a senior citizen (I cut my programming teeth back using punch cards and Structured Basic when it first came out). If anyone needs more clarification of what I am trying to accomplish please let me know.  Thanks in advance for any assistance/advice.