Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

UI button triggering a change of scene after an animation has finished (I'm new please help!)

Discussion in 'Scripting' started by uqmyou13, Apr 18, 2020.

  1. uqmyou13

    uqmyou13

    Joined:
    Mar 28, 2020
    Posts:
    5
    When I press a UI button I need to trigger an animation followed by changing the scene (after the animation has finished). Both of my sets of code work individually, however I am unsure of how to merge them and to ensure the change of scene doesn't happen until after the animation has finished. I am new to unity so any help would be useful! Thanks :)

    This is the code I have at the moment to trigger the animation.

    Code (CSharp):
    1. public class LeftButtonPress3 : MonoBehaviour {
    2.  
    3.     public Button Text;
    4.     public Animator ani;
    5.     public Canvas yourcanvas;
    6.  
    7.     void Start() {
    8.         Text = Text.GetComponent<Button>();
    9.         ani.enabled = false;
    10.         yourcanvas.enabled = true;
    11.     }
    12.  
    13.  
    14.     public void Press() {
    15.         Text.enabled = true;
    16.         ani.enabled = true;
    17.         ani.Play("Fisherman - Left 3");
    18.     }
    19. }
    20.  
    This is the code I have at the moment to change the scene.

    Code (CSharp):
    1. public class GoToScene1 : MonoBehaviour {
    2.    
    3.     public void ChangeScene(string sceneName) {
    4.         SceneManager.LoadScene(sceneName);
    5.     }
    6. }
     
  2. arfish

    arfish

    Joined:
    Jan 28, 2017
    Posts:
    777
    Hi,

    Then you need to delay the scene change till the clip is done.
    One way is to check if the clip is playing, and another is to just wait for the length of the clip in seconds.

    For example like this, with a coroutine (haven't tested the code though).
    First the coroutine:
    Code (CSharp):
    1.  
    2. IEnumerator DelayedSceneChange(float delay, string sceneName)
    3. {
    4.     yield return new WaitForSecondsRealtime(delay);
    5.     ChangeScene(sceneName);
    6. }
    Then the call to it when the button is pressed:
    Code (CSharp):
    1. StartCoroutine(DelayedSceneChange(length_of_clip, sceneName));
     
    uqmyou13 likes this.
  3. uqmyou13

    uqmyou13

    Joined:
    Mar 28, 2020
    Posts:
    5
    Thank you, this helped a lot! :)