1

I have a System.Serializable class

[System.Serializable]
public class _answersData
{
    public string word;
    public string wordmeaning;
    public string wordmeaning2;
    public GameObject result;    
}

I then have a monobehaviour class where an array of _answerData class is declared

public class gamePlay : MonoBehaviour
{
    public _answersData[] answersData;
}

I am then trying to add data to _answerData array from another script using below method

public class challengeScript: MonoBehaviour
{
    void Start()
    {
        gameplayScript = gameObject.GetComponent<gamePlay>();
        populate();
    }
    
    void populate()
    {
        answersCount = int.Parse(snapshot.Child("Answers").Child("Count").Value.ToString());
        gameplayScript.answersData = new _answersData[answersCount];

        for (int i = 0; i < answersCount; i++)
        {
            string positionNode = "Answer" + (i + 1).ToString();
            string _word = snapshot.Child("Answers").Child(positionNode).Child("Word").Value.ToString();
            gameplayScript.answersData[i].word = _word;   
        }
    }
}

but I am getting NullReferenceException at 'gameplayScript.answersData[i].word = _word' line

Here's the error:

NullReferenceException: Object reference not set to an instance of an object

Can someone guide what I am doing wrong here?

1 Answer 1

1

Just because it is [Serializable] doesn't mean the elements are automatically created once you create the array. By default all reference type elements will still be null.

Only within Unity the Inspector itself automatically creates instances of [Serializable] types and initializes the array itself.

In code you have to actually create your element instances yourself like e.g.

var answerData = new _answerData();
answerData.word = _word;
gameplayScript.answersData[i] = answerData;  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.