[SOLVED] Loop alternative option?

ForLoop

@Rick_Davidson

Hi Rick, I have a little question for you.

I do not know if this is a good programming behavior but instead of using the loop I did what I show in the picture. I declared 4 options in the next state (that is currently the total amount of possible keys that can be pressed in my code), the ones hat I do not want any action when pressed are declared as “none(state)” and is working good, no error is appearing. Is something wrong with this way or can lead to any future problem?

My code:

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

private void ManageState()
{
    var nextState = state.GetNextState();

    if(Input.GetKeyDown(KeyCode.Alpha1))
    {
        state = nextState[0];
    }

    else if (Input.GetKeyDown(KeyCode.Alpha2))
    {
        state = nextState[1];
    }

    else if (Input.GetKeyDown(KeyCode.Alpha3))
    {
        state = nextState[2];
    }

    else if (Input.GetKeyDown(KeyCode.Return))
    {
        state = nextState[3];
        TextComponent.alignment = TextAnchor.MiddleLeft;
    }

    TextComponent.text = state.GetStateStory();
}

Hi Sergio,

What happens if you play your game? Do any red error messages appear in your console when you press “1” in your A0 state?

Hi Nina,

no error message appears, that was the first thing I checked, is working just fine, but might this way of programming bring any problem in the code, or be slower than doing the loop ? I did not check what happens if you press multiple key a the same time, but I will do it.!

Actually, you should get a red NullReferenceException because your code tries to access an non-existing object. In some cases, errors like that can prevent your game from working correctly. For this reason, these errors should get fixed.

An error message that does not appear does not mean that there is no error. If the console does not show it even though you know that it should have appeared, you have a big problem because the console is one of the most important tools when developing your game.

I’ve noticed that your version of Unity is an alpha version. Please do not use an alpha or beta version for your actual projects. They are full of bugs. Downgrade to a stable version with an “f” in its version number. Maybe the error messages will appear when you do that.

1 Like

OH!! I see, that might be the reason, so I will do that immediately… Thanks for you answer Nina! and if for any reason I´m having the same problem I´ll let you know.

You’re welcome. I hope downgrading fixed the issue with your console. :slight_smile:


See also:

1 Like

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

Privacy & Terms