- Home /
How to play multiple audio files from one script
I have been working on a platformer, and I am trying to have both a jump sound play (already have it) and a coin sound play (don't have this one) my code is bellow, what do I have to do? I have tried a lot of things, so the coin sound is not implemented below right now. using System; using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController2D controller; public Animator animator; public float runSpeed = 40f; AudioSource jumpSound; float HorizontalMove = 0f; bool Jump = false; bool Crouch = false; void Start() { jumpSound = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { HorizontalMove = Input.GetAxisRaw ("Horizontal") * runSpeed; animator.SetFloat("speed", Mathf.Abs(HorizontalMove)); if (Input.GetButtonDown("Jump")) { Jump = true; jumpSound.Play(); animator.SetBool("isJumping", true); } if (Input.GetButtonDown("Crouch")) { Crouch = true; } else if (Input.GetButtonUp("Crouch")) { Crouch = false; } } public void onLanding() { animator.SetBool("isJumping", false); } public void onCrouching(bool IsCrouching) { animator.SetBool("isCrouching", IsCrouching); } void FixedUpdate() { //move our charactor controller.Move(HorizontalMove * Time.fixedDeltaTime, Crouch, Jump); Jump = false; } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Coin")) { Destroy(other.gameObject); } } }
Answer by finnjwohner · Jul 12, 2020 at 04:46 AM
You could have 2 AudioSources on the same object and just assign those to variables in script like this;
private AudioSource jumpSound;
private AudioSource coinSound;
private void Start() {
jumpSound = GetComponents<AudioSource>()[0];
coinSound = GetComponents<AudioSource>()[1];
}
And then just invoke Play() whenever you want to play either sound. Keep in mind if you do this then the order of the AudioSources matters in the inspector (Jump sound audio source should come first, then coin sound).