Cannot Apply Indexing [ ] to an expression of type object (UNITY 2D CLASSES)

I keep getting an error on nextStates on VS, sayinh that “Cannot Apply Indexing to an expression of type object”. I have the same code as in your examples. How can i fix this?

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

public class AdventureGame : MonoBehaviour
{

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

State state;

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

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

private void ManageState()
{
    var nextStates = state.GetNextStates();
    if (Input.GetKeyDown(KeyCode.Alpha1))
    {
        state = nextStates[0];
    }
    
}

}

!
!
New%20Bitmap%20Image%202|690x388 New%20Bitmap%20Image

What does GetNextStates() return? Make sure it returns an array of States, not just a single State object, since otherwise you won’t be able to access elements of it.

Hope this helps!
~ Jonny

1 Like

I am a total noob, and have no idea. what is wrong. everything that you see in the code is what I saw in the tutorial. I will try from scratch this lesson, to see what I can do. But I would like to understand what the error log means.

Thanks

Hi Rolando,

Have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture?

What @jonnyf3 meant is how you declared your method.

public void GetNextStates() { }?
public State GetNextStates() { }?
public State[] GetNextStates() { }?

Next to the public access modifier, you can find the return type.

So the solution was, that when I was typing GetnextStates, in VS, there where 2 options one that defined it as OBject, and one thta defined as a State, i was using the one as Object by mistake.

Take care! and thanks!

I’m glad you were able to fix the issue. :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms