How do I play an audiofile as long as a key is pressed?

Hello folks,

I am totally new to c# and Unity, but I tried to write a script to play audio files, as long as I hold down a key.

using UnityEngine;
using System.Collections;

public class PlayMusic : MonoBehaviour {
   
    public AudioSource Interest;
    public AudioSource Stress;
    public AudioSource Relaxation;


    void Update() {

        if ( Input.GetKey("e")) {
            Interest.Play ();
            Stress.Stop ();
            Relaxation.Stop ();
        }


        if (Input.GetKey("r")) {
            Stress.Play ();
            Interest.Stop ();
            Relaxation.Stop();
        }


        if (Input.GetKey("t")) {
            Relaxation.Play ();
            Interest.Stop ();
            Stress.Stop ();
        }
    }   
}

But if I hold down one of the keys, the sound starts playing again and again (just the first tone). How do I have to adapt the script to play the sound only one time, as long as the key is hold down?

Thanks in advance!

use KeyCodeCode…

if (Input.GetKey(KeyCode.KEY))

That you you don’t have to rely on strings…

This has the same effect on the audio file. As long as I hold down the key, Unity thinks it has to play the audio over and over again from start instead of playing it one time through.

Use GetKeyDown to start playing and GetKeyUp to stop playing.

1 Like

Thank you, it worked! I totally forgot tha I can use GetKeyUp as well.