i have a mini text game here , and i have an if statement but the user can execute what’s inside else if before the If one and that breaks the game , how do i prevent that
my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainScript : MonoBehaviour
{
StateScript State;
[SerializeField] Text PlayerHp;
[SerializeField] Text StoryText;
[SerializeField] StateScript FirstState;
// Start is called before the first frame update
void Start()
{
State = FirstState;
StoryText.text = State.GetStoryLine();
PlayerHp.text = State.GetPlayerHp();
}
// Update is called once per frame
void Update()
{
ManageStates();
}
void ManageStates()
{
StateScript[] NextState = State.GetNextStates();
for (int index = 0; index < NextState.Length; index++)
if (Input.GetKeyDown(KeyCode.Alpha1 + index))
{
{
State = NextState[index];
}
}
else if (Input.GetKeyDown(KeyCode.Return))
{
State = NextState[0];
}
StoryText.text = State.GetStoryLine();
PlayerHp.text = State.GetPlayerHp();
i understand what I want but I was just saying that there are many things wrong with this code, anyway here is a way to do what you want:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainScript : MonoBehaviour
{
StateScript State;
[SerializeField] Text PlayerHp;
[SerializeField] Text StoryText;
[SerializeField] StateScript FirstState;
public bool secondIFallowed = false;
// Start is called before the first frame update
void Start()
{
State = FirstState;
StoryText.text = State.GetStoryLine();
PlayerHp.text = State.GetPlayerHp();
}
// Update is called once per frame
void Update()
{
ManageStates();
}
void ManageStates()
{
StateScript[] NextState = State.GetNextStates();
for (int index = 0; index < NextState.Length; index++)
if( secondIFallowed == true){
if (Input.GetKeyDown(KeyCode.Return))
{
State = NextState[0];
secondIFallowed = false;
}
}
if (Input.GetKeyDown(KeyCode.Alpha1 + index))
{
{
State = NextState[index];
secondIFallowed = true;
}
}
StoryText.text = State.GetStoryLine();
PlayerHp.text = State.GetPlayerHp();
also its really messy that you dont have brackets on your for loop