Problem with getting the code to run: " An object reference is required for the non-static field, method or property 'State.GetStateStory()' "

I get the error message " An object reference is required for the non-static field, method or property ‘State.GetStateStory()’ "

I have no idea how to fix this and I’ve searched the internet quite a bit. Any help would be greatly appreciated!

State.cs:

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

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

    public string GetStateStory()
    {
        return storyText;
    }
}

AdventureGame.cs

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

public class AdventureGame : MonoBehaviour
{

    [SerializeField] Text textComponent;
    [SerializeField] State startingState;

    State currentState;

    // Use this for initialization
    void Start()
    {
        currentState = startingState;
        textComponent.text = State.GetStateStory();
    }

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

    }
}

Hi Jake, welcome to the community :slight_smile:

Your error is because you are trying to access the method, GetStateStory, via the class State rather than an instance of it.

You have declared a variable, startingState but are not using it. You also have currentState.

From memory, the variable you have called currentState was called state in the course, which is probably where your confusion has come from.

Change this line;

textComponent.text = State.GetStateStory();

to

textComponent.text = currentState.GetStateStory();

Also, please apply the code formatting characters when copy/pasting your code into the forum.

Hope this helps. :slight_smile:


See also;

Hi Rob,

Thanks for the help, I really appreciate it! :slight_smile:

1 Like

You’re very welcome Jake, I’m glad you can move forward again :slight_smile:

Privacy & Terms