0

I have a problem, probably coming from my inexperience, I want to add an upgrade menu with two buttons. If you click the first button, hp gets a boost and then I want to make it disable itself, but that's another story. The same goes for the second button, but this time it boosts the damage. The code is my UpgradeMenuUI, which is placed under a GUI element GmaeOBject, is as follows.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;    

public class UpgradeMenuUI : MonoBehaviour {    

    private Stats stats;
    private DamageScript dmg;    

    public void HpUpgrade()
    {
       line 16 error// stats.maxVal += 20;
    }

    public void DmgUpgrade()
    {
        same error for this button// dmg.playerDamage += 10;
    }
}

In my DamageScript script, there is a public int player damage; , which I access here and for the health, it's from the Stats script, where I link it with a UI Health Bar:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class Stats
{
    [SerializeField]
    private BarScript bar;
    public float maxVal;
    public float currentVal;

    public float CurrentVal
    {
        get
        {
            return currentVal;
        }

        set
        {
            this.currentVal = Mathf.Clamp(value, 0, maxVal);
            bar.Value = currentVal;
        }
    }

    public float MaxVal
    {
        get
        {
            return maxVal;
        }    
        set
        {
            this.maxVal = value;
            bar.MaxValue = value;
        }
    }

    public void Initialize()
    {    
        this.MaxVal = maxVal;
        this.CurrentVal = currentVal;
    }
}

All I want is when I click the buttons the corresponding unit to improve. I add the voids through a OnClick for each button, but when I press any of my two buttons, I get this error:

NullReferenceException: Object reference not set to an instance of an object UpgradeMenuUI.HpUpgrade () (at Assets/Scripts/Level1/UpgradeMenuUI.cs:16) UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at

Its really long and this is the first part.

Any ideas? Thanks!

Alex Myers
  • 6,196
  • 7
  • 23
  • 39
TheNewbie
  • 323
  • 2
  • 9
  • 22
  • Initialize `stats` variable in the `UpgradeMenuUI` script. Since the `Stats` script does not inherit from `MonoBehaviour`, you can do that with the `new` keyword. Just add this: `void Awake() { stats = new Stats(); }` – Programmer Nov 12 '17 at 20:33
  • There is no default constructor in C# so when you declare "private Stats stats;" you actually declare a pointer to a Stats object that doesn't exist yet: it points to nothing => NullRef exception when you try to do "stats.maxVal += 20;" because stats is null (it's a pointer to nothing). To fix this, you have to initialize stats like explained in the comment above. – Pierre Baret Nov 13 '17 at 19:16

0 Answers0