简体   繁体   中英

Pause music on keyboard input

I have an audio source attached to my game object and i want the music to pause when the keyboard up arrow is pressed and unpause when the keyboard down arrow is pressed.

Why is this not working?

public class pauseMusic : MonoBehaviour {


public AudioSource audio;

// Use this for initialization
void Start () {

    audio = gameObject.GetComponent<AudioSource>();

}

// Update is called once per frame
void Update () {

    if(Input.GetKey(KeyCode.UpArrow)) {
        audio.pause();
    }


    if(Input.GetKey(KeyCode.DownArrow)) {
        audio.UnPause();
    }

}
}

You didn't capitalize the "p" of of pause. So your program doesn't recognize the Pause function.

You by the way probably prefer to use the GetKeyDown method over the GetKey one, as you want to pause or unpause your audio only once, and not everytime you enter in your update.

void Update () {

    if(Input.GetKeyDown(KeyCode.UpArrow)) {
        audio.Pause();
    }


    if(Input.GetKeyDown(KeyCode.DownArrow)) {
        audio.UnPause();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM