Hi Hersh,
Good job on solving the problem.
I’ve read your code, and it looks fine. If it works, it is a solution by definition.
The local probState() method can be dropped as it contains only one line of code and gets called all the time anyway.
private void ManageStates()
{
var nextStates = state.GetNextStates();
var altStates = state.GetAltStates();
var prob = 0; // could be a local variable
for (int index = 0; index < nextStates.Length; index++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + index) && index < altStates.Length)
{
prob = UnityEngine.Random.Range(1, 11);
if (prob <= 4)
{
state = altStates[index];
}
else
{
state = nextStates[index];
}
}
else if (Input.GetKeyDown(KeyCode.Alpha1 + index))
{
state = nextStates[index];
}
}
textComponent.text = state.GetStateStory();
}
And then you could optimise the performance a bit because it is not neccesary to check Input.GetKeyDown(KeyCode.Alpha1 + index)
twice.
private void ManageStates()
{
// if no key was pressed, terminate the method
if (!Input.anyKey) { return; }
var nextStates = state.GetNextStates();
var altStates = state.GetAltStates();
for (int index = 0; index < nextStates.Length; index++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + index)
{
if (index < altStates.Length)
{
int prob = UnityEngine.Random.Range(1, 11);
// ternary operator
state = (prob < 5) ? altStates[index] : nextStates[index];
}
else
{
state = nextStates[index];
}
textComponent.text = state.GetStateStory();
break; // leave the for-loop
}
}
}
Does that make sense?
Your solution was perfectly fine. I just showed you how to optimise it because you asked for feedback. Keep up the good work!