2
\$\begingroup\$

I want to make play and pause buttons to play and pause sound and also I want it to play and pause animation ,how should I do that?

//function 
 public void TogglePlay()
    {
        if (audio.isPlaying)
        {
            audio.Pause();
        }
        else
        {
            audio.Play();
        }
    }
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Animator has a speed property. If you set it to 0, it will stop playing. Then set it back to 1 to resume playback.

public void TogglePlay()
{
    if (audio.isPlaying)
    {
        audio.Pause();
        animator.speed = 0;
    }
    else
    {
        audio.Play() ;
        animator.speed = 1;
    }
}
\$\endgroup\$
0
\$\begingroup\$

I would use an AudioSource, because this can change between multiple AudioClip, which is a specific sound, so you can play multiple sounds.

You'll have to attach all needed components in editor before this.

  1. An AudioSource component to your AudioSource field and drag the AudioClip into that AudioSource Component.
  2. A Button component on the btnMusic field.
  3. An Animator on the animator field and create an animation in the Animator tab in the editor.

Then in your GameManager you can do something like this:

public AudioSource audioSource;
public Animator animator;
public Button btnMusic;

void Start()
{
    audioSource.Play("name-of-your-audio-clip");
    btnMusic.onClick.AddListener(BtnMusicOnClick);
}

void BtnMusicOnClick(){
    if (audioSource.isPlaying) {
        audioSource.Pause();
    } else {
        audioSource.UnPause();
    }
    animator.Play("btnMusicOnClick");
}
\$\endgroup\$
3
  • \$\begingroup\$ I use animator not animation \$\endgroup\$
    – Sh.Adel
    Commented Dec 16, 2018 at 12:15
  • \$\begingroup\$ @Sh.Adel it works the same, I've updated the example. Let me know how it goes. \$\endgroup\$ Commented Dec 16, 2018 at 12:28
  • \$\begingroup\$ this play animation how to pause it if sound paused?(pause animation not stop it) \$\endgroup\$
    – Sh.Adel
    Commented Dec 17, 2018 at 7:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .