berdyev berdyev - 1 year ago 114
C# Question

Unity3d C# Adding/Subtracting health using inventory item

I have a little problem here that I've been trying to fix for past couple of hours. I'm using Unity 5 and c# to code with.

I have PlayerScript which has health/thirst/hunger values for the player.

I also have another script that works as the inventory. I've added the item "water" which you as a player can consume.

Here's some code for you to understand more:


public float health = 100f;
public float hunger = 100f;
public float thirst = 100f;


if (consumeEffects[i] == "DrinkItem")
GameObject.Find ("FPSController").GetComponent<PlayerScript>().thirst += 25.0f;
Debug.Log("You drank some water!");

So basically, I have an item that has Consume category and DrinkItem element ~ which means that when I try to consume for example: water, it should add 25 water to the thirst. But it doesnt!

I know it works because I can see the debug message, but at the same time I get an error:

NullReferenceException: Object reference not set to an instance of an object
UI_Hotbar.ActivateItem (Int32 index) (at Assets/UI_Hotbar.cs:120)

Line 120 includes the line where we add 25 to the thirst. Trying to see whats wrong with the UI hotbar in hierarchy doesn't give me answers. Everything looks just fine.

Someone please help? Thanks in advance!

Answer Source

With the Image upload in your comment section,PlayerScript is not attached your FPSController GameObject. That's why GetComponent<PlayerScript>() is failing. You must attach PlayerScript script to your FPSController GameObject.

You can either do that from the Editor or through script in the Start() function GameObject.Find("FPSController").AddComponent<PlayerScript>();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download