Problem with GetStartingState();

Problem with GetStartingState();. What’s wrong with my code?? There’s some null value problem too!
See the screenshots.




Thanks for any help!!

Hi Tejas,

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

Regarding the message in your Console, NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

Hope this helps :slight_smile:


See also;

Hi Nina,

Below I have the code and the line the error is referring to. I would really appreciate your help on how to fix the error.

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

[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
    [TextArea(14, 10)] [SerializeField] string storyText;

    public string GetStateStory()
    {
        return storyText;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AdventureGame : MonoBehaviour
{
    [SerializeField] Text textComponent;
    [SerializeField] State startingState;

    State state;
    // Start is called before the first frame update
    void Start()
    {
        state = startingState;
        textComponent.text = state.GetStateStory(); // this line is the one with the error
    }

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

The error says:

“NullReferenceException: Object reference not set to an instance of an object
AdventureGame.Start() (at Assets/AdventureGame.cs: 16)”

Thank you for formatting your code.

In the line with textComponent.text = state.GetStateStory();, there are two variables that can be null: textComponent and state.

Make sure that you assigned the game object with the Text component to the Text Component variable in the Inspector of your Adventure Game.

Is a State object assigned to the Starting State variable?

1 Like

This topic was automatically closed after 14 days. New replies are no longer allowed.

Privacy & Terms