Search Unity

Button gives NullRefranse..

Discussion in 'Scripting' started by johnbjoekne, Oct 2, 2018.

  1. johnbjoekne

    johnbjoekne

    Joined:
    Aug 9, 2018
    Posts:
    2
    I looked this up and down now and i can't figure it out.

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

    public class Buttoncontroller : MonoBehaviour {

    public Button numInc, numDec;
    private int age;
    public Text ageCount;

    // Use this for initialization

    void Start () {
    Button btn1 = numInc.GetComponent<Button>();
    btn1.onClick.AddListener(TaskonClickInc);

    Button btn2 = numDec.GetComponent<Button>(); //Line 24
    btn2.onClick.AddListener(TaskonClickDec);
    }

    // Update is called once per frame
    void Update () {

    if (age <= 0 )
    {
    age = 14;
    }
    ageCount.text = ""+ age;
    }

    void TaskonClickInc()
    {
    if (age >= 40)
    {
    age = 40;
    }
    else if (age <= 39)
    {
    age ++;
    Debug.Log("AgeIncreased");
    }
    }
    void TaskonClickDec()
    {
    if (age >= 15)
    {
    age --;
    }
    else if (age <= 14)
    {
    age = 14;
    }
    Debug.Log("AgeDecreased");
    }

    }


    The first Button (Btn1) works fine but the Btn2 gives:

    NullReferenceException: Object reference not set to an instance of an object
    Buttoncontroller.Start () (at Assets/Script/UI/Buttoncontroller.cs:24)

    I have also assigned them in the unity engine so thats not the problem either. It's probably simple i am just new to this.
     
  2. Mauri

    Mauri

    Joined:
    Dec 9, 2010
    Posts:
    2,664
    Are you sure that you've assigned everything correctly? Because your code works for me. Tested it and there were no errors showing. It increases and decreases the number as intended...
     
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Post code using code tags. Your issue is numDec is null. I also don't understand why you are calling numDec.GetComponent<Button>() when numDec is already a Button reference, and the same with numInc a few lines up.
     
  4. johnbjoekne

    johnbjoekne

    Joined:
    Aug 9, 2018
    Posts:
    2
    Thank you both. When i tried again now, after several hours...it suddenly , magically worked...no errors showed up and now changes had been made. sometimes i think the program is getting old:p and ill remember the codetag, thanks joe. :)