- Home /
Instance not found only when using button press to execute function,Canvas instance not found when executing function via button press
I am creating a game in which players are asked a question and then have the opportunity to give an answer on time. When the time runs out, the text is sent in its current form and alternatively you can press a button if you finish earlier.
I generate a canvas with the UI and store it in a variable, then I start a coroutine in which it waits for an answer and after waiting, as well as when the button is triggered, the same function (StopAskForInput()) is called, which outputs the answer in the Debug.Log and destroys the canvas.
Strangely enough, when I trigger the button, an error comes up claiming that my canvas is not initialized (at the Debug.Log line) but when the time is up and the coroutine is finished, the same function works fine.
public class Player: MonoBehaviour
{
Canvas inputFieldCanvas;
.
.
.
.
void ShowQuestion()
{
.
.
.
inputFieldCanvas = UIManager.GenerateInputTextPopup();
StartCoroutine(AskForInput(5));
}
public IEnumerator AskForInput(int seconds)
{
yield return new WaitForSeconds((float) seconds);
StopAskForInput();
}
public void StopAskForInput()
{
StopCoroutine("AskForInput");
Debug.Log(inputFieldCanvas.GetComponentInChildren<TMP_Text>().text);
Destroy(inputFieldCanvas.gameObject);
}
}
Your answer
Follow this Question
Related Questions
Problem with coroutine. 2 Answers
Highlighted buttons stay highlighted when I deactivate a canvas. No way to unhighlight them. 1 Answer
UI Buttons Not Working in Dual Screen Setup 0 Answers
Unity UI Position 2 Answers
Scale Layout elements to fit screen 2 Answers