play music in void update()

Hi all,

My problem is the following:

I am making a simple unity game with C#, and i need that game over music starts when the ball (that is the player) was placed under -5 in y axis. I have achieved to stop background music, but i am not able to play the game over music. It sounds only a second decimal and stop. I belive that it is because i am doing it in update method. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Jugador : MonoBehaviour
{

public float velocity;
private Rigidbody fisic;
private int points;
private Transform position;
public Text gameOver;
private GameObject camera;

// Start is called before the first frame update
void Start(){

fisic = GetComponent();
position = GetComponent();
camera = GameObject.FindGameObjectWithTag(“camera”);

}

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

float movimientoHorizontal = Input.GetAxis(“Horizontal”); //horizontal movement
float movimientoVertical = Input.GetAxis(“Vertical”); //vertical movement

Vector3 movimientos = new Vector3(movimientoHorizontal, 0, movimientoVertical);
fisic.AddForce(movimientos * velocity);

//we control when the ball falls into empty space
if (position.localPosition.y < -5) {

gameOver.text = “GAME OVER”;
managerMusic();

}

}

void managerMusic() {

camera.GetComponent().Stop(); // it works
GetComponent().Play(); // it doesnt work !!!

}

void OnGUI(){

GUI.Box(new Rect(0, 0, 80, 35), "Score: " + points);

}

private void OnTriggerEnter(Collider collision){

if (collision.CompareTag(“coin”)) {
points++;
}

}

}

Well, remember Update runs every frame, so you’ll end up calling play repeatedly which may just keep restarting the music over and over. For a game over type thing, you should just have a method you call for Game Over that stops current music and starts the game over music along with any other text you want.

Also, just make sure your AudioSource is also on the same gameobject as this script is on.

4146526--365281--code.PNG
Also, please use the code tag.

ok, thanks

Turning the issue over, it occurred to me to create a game object “lower limit” that when it is traversed by the ball call the onTriggerEnter method and in that way stop the music and reproduce the game over

Have you thought about having a bool in the GameOver method so that it runs only once even if u call it from update? Would be much more efficient and clean. Aka GameOver()
{ if(!gameOver)
gameOver = true;
//do your game over stuff. }

1 Like