Hello. I’ve been following tutorials to learn unity and C#. Following a tutorial I’ve implemented a system that shows the player a choice box. The choice box works fine as implemented in the tutorial, but when I want to expand this into other game scenarios it does not work. This is the implementation of the code that doesn’t work:
public void HandleUpdate(Action<int> onSelected)
{
if (choosing)
{
if (Input.GetKeyDown(KeyCode.DownArrow))
currentSlot += 2;
else if (Input.GetKeyDown(KeyCode.UpArrow))
currentSlot -= 2;
else if (Input.GetKeyDown(KeyCode.LeftArrow))
--currentSlot;
else if (Input.GetKeyDown(KeyCode.RightArrow))
++currentSlot;
}
currentSlot = Mathf.Clamp(currentSlot, 0, Moves.Count);
UpdateMoveSelection(currentSlot);
if (Input.GetKeyDown(KeyCode.Z))
{
StartCoroutine(Confirm(onSelected));
}
}
IEnumerator Confirm(Action<int> onSelected)
{
int selectedChoice = 0;
choosing = false;
yield return choiceBox.ShowChoices(new List<string>() { "Yes", "No" }, (choiceIndex) => selectedChoice = choiceIndex);
if (selectedChoice == 0)
{
// Yes, continue
choosingMove = true;
onSelected?.Invoke(currentSlot);
}
else if (selectedChoice == 1)
{
// No, go back
SetMessageText("Which move should be forgotten?");
choosing = true;
yield break;
}
}
And this is the choice box scritp:
public IEnumerator ShowChoices(List<string> choices, Action<int> onChoiceSelected)
{
gameObject.SetActive(true);
choiceSelected = false;
currentChoice = 0;
choiceTexts = new List<ChoiceText>();
// Delete existing choices
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
// Instantiate new choices
foreach (var choice in choices)
{
var choiceTextObj = Instantiate(choiceTextPrefab, transform);
choiceTextObj.TextField.text = choice;
choiceTexts.Add(choiceTextObj);
}
yield return new WaitUntil(() => choiceSelected == true);
onChoiceSelected?.Invoke(currentChoice);
gameObject.SetActive(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
++currentChoice;
else if (Input.GetKeyDown(KeyCode.UpArrow))
--currentChoice;
currentChoice = Mathf.Clamp(currentChoice, 0, choiceTexts.Count - 1);
for (int i = 0; i < choiceTexts.Count; i++)
{
choiceTexts[i].SetSelected(i == currentChoice);
}
if (Input.GetKeyDown(KeyCode.Z))
{
choiceSelected = true;
}
}
For some reason that I don’t understand, when the ShowChoices Coroutine ends the value that the Action passes through the choiceIndex parameter to the selectedChoice variable is always 0, so no mather what the player selects, only the first option gets executed.
I tried debugging and the currentChoice variable that controls which option is selected and is passed through the Action does work and its value changes between 0 and 1 as intended. I tried forcing the selectedChoice variable that triggers the Action to 1 and its value does change to 0.
Can someone please explain to me why does it happen and how can I solve it? I feel like I’m overseeing something stupid that I just can’t find.
Thank you.