GameAdventure.cs that dynamically generates choices and input checks

Hello everyone, i’ve worked on a code that dynamically generates the game text and look for player choices based on the current nextStates.

My GameAdventure.cs script file:

using UnityEngine;
using UnityEngine.UI;

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

    State state;
    State[] nextStates;
    // Start is called before the first frame update
    void Start()
    {
        state = startingState;
        nextStates = state.GetNextStates();
        textComponent.text = ComposeText();
    }

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

    private string ComposeText() 
    {
        string finalText = "";
        finalText += state.GetStateStory() + "\n";
        for (int i = 0; i < nextStates.Length; i++)
        {
            finalText += "\n" + (i + 1) + ". " + nextStates[i].GetChoiceText();
        }
        return finalText;
    }

    private void getPlayerChoice() {
        for(int i = 0; i < nextStates.Length; i++) {
            if (Input.GetKeyDown((i+1).ToString())) {
                state = nextStates[i];
            }
        }
    }

    private void updateText() {
        nextStates = state.GetNextStates();
        textComponent.text = ComposeText();
    }
        
}

1 Like

Thank you for this. Awesome code!

Privacy & Terms