简体   繁体   中英

Child to parent class Object Reference not set to an instance of an Object C#

I am very new to inheritance in C# and my problem is Object Reference not set to an instance of an object from Parent to Child

I tried the debug log from string to parent to child and works now that im experimenting this happens now

This my parent class

public class GameManagerRevamped : MonoBehaviour
{
    //Arrays Buttons
    public GameObject[] gameButtons;

    //Arrays ImagesSource
    public Image[] ImagesSource;
    //Source Images
    public Sprite[] BlackImages;

    //Instance Variables
    public int ImagesClick =-1;
    public int buttonOrder;
    public string finalAnswer = "";
    public string TryInheritance;

    public virtual void buttonClicked()
    {
        ImagesSource[ImagesClick].sprite = BlackImages[ImagesClick];
        gameButtons[buttonOrder].SetActive(false);
    }

    public virtual void firstButtonClicked()
    {
        ImagesClick += 1;
        buttonOrder = 0;
        buttonClicked();
        finalAnswer += "";
        Debug.Log(TryInheritance);
    }
}

this my Child Class

public class FableScript : GameManagerRevamped
{

    public override void buttonClicked()
    {
        base.buttonClicked();
    }

    public override void firstButtonClicked()
    {   
        finalAnswer += "f";
        TryInheritance =finalAnswer;
        ImagesClick += 1;
        buttonOrder = 0;
        buttonClicked();
        base.firstButtonClicked();
    }
}

The "TryInheritance" works but the other is on not set to instance object. Point is when I click on the button the it goes to inactive state :))

It's not entirely clear from the original question where the exception is being thrown, but it does look very strange that you repeat a number of lines of firstButtonClicked in the derived (child) class before then calling the method in the base (parent) class.

When you follow the code path, for example, ImagesClick gets incremented twice (once in the derived class and then once in the parent class, the same happens with buttonClicked() and my guess (because I don't know the implementation) is that the button goes inactive because buttonClicked() is called twice.

One of the advantages of inheritance is that you do not need to repeat common code. Your derived class firstButtonClicked method might work with just:

public override void firstButtonClicked()
{   
    finalAnswer += "f";
    TryInheritance =finalAnswer;
    base.firstButtonClicked();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM