- Home /
Starting coroutine from button does not work as expected
Hi, I have a dialogue box which is able to pop up and pop out using coroutines. Here's the code for the IEnumerator methods:
public IEnumerator Popup(){
var t = 0f;
while(t < 1f){
var newScale = Mathf.SmoothStep(0f, 1f, t);
transform.localScale = new Vector3(newScale, newScale, 1f);
t += Time.deltaTime * animationSpeed;
yield return null;
}
transform.localScale = new Vector3(1f, 1f, 1f);
}
public IEnumerator Popout(){
var t = 0f;
while (t < 1f){
var newScale = Mathf.SmoothStep(1f, 0f, t);
transform.localScale = new Vector3(newScale, newScale, 1f);
t += Time.deltaTime * animationSpeed;
yield return null;
}
transform.localScale = new Vector3(0f, 0f, 1f);
gameObject.SetActive(false);
}
Currently I have StartCoroutine(Popup())
called in Update()
while in Start()
I have buttonImage.GetComponent<Button>().onClick.AddListener(() => StartCoroutine(Popout()))
.
My end result was this:
For some reason the popout coroutine does not get showed properly when using the button. I've tested the coroutine itself by calling it directly in Update()
and the dialogue box pops out as expected.
Am I missing something? Thanks in advance.
Answer by Bunny83 · Nov 28, 2019 at 04:36 AM
Currently I have StartCoroutine(Popup()) called in Update()
Uhm why? When you call StartCoroutine in Update you start a new coroutine every frame. If you want to show the popup at the start of your game you should place StartCoroutine(Popup()); in Start so it gets started once. Currently when you start your "Popout" coroutine you have hundreds of Popup coroutines running at the same time.
Yup I am a complete idiot for not even noticing that. Seems weird then that it doesn't just completely break the popup animation if it's being called every frame. Thanks for your help!
Answer by Larry-Dietz · Nov 28, 2019 at 04:01 AM
Instead of trying to add a startcoroutine as a listener, How about creating a method StartPopOut() and assign it to be run on click, and start the coroutine from within that method?
Hope this helps, -Larry
Your answer

Follow this Question
Related Questions
Problem with coroutine. 2 Answers
Graphics Raycaster - Click on overlapped buttons 1 Answer
Unity5 UI - How to trigger button click event while preventing menu item deselect event? 1 Answer
Displaced UI RectTransform collider in some resolutions issue. 1 Answer
How can I have a UI ScrollRect still scroll if pressing a button inside of it? 1 Answer