- Home /
Change Music When GameObject is Grabbed?
Hello again for the 1000th time awesome people of Unity Answers, I have a question as always. I managed to get my music to changed to a different track when I grab a certain gameobject, however when I grab the gameobject again it changes back to the first music track. My question is, how can I stop it from changing back to the first track, and instead just restart the second track over? Example: Track 1 plays, grabs gameobject, Track 2 plays for 10 seconds, grabs the gameobject again, Track 2 replays starting at 0 seconds(the beginning). Here's my music and how it changes so far:
public float defaultSpeed = 5f;
public float maxSpeed = 10f;
public AudioClip[] songs;
AudioSource audio;
public float coeffSpeedUp = 5f;
public float coeffSpeedUpTime = 5f;
// Use this for initialization
void Start ()
{
audio = GetComponent<AudioSource> ();
audio.clip = songs [0];
audio.Play ();
}
public void SpeedUp()
{
Debug.Log( "SpeedUp()" );
// Speed up the player
speed = defaultSpeed * coeffSpeedUp;
audio.Stop (); //pauses the Track 1
audio.clip = songs [1]; //gets the Track 2
audio.Play (); // plays Track 2
CancelInvoke ("EndSpeedUp"); // in case the method has already been invoked
Invoke ("EndSpeedUp", coeffSpeedUpTime = 5 );
}
void EndSpeedUp()
{
//Changes how fast the player goes
Debug.Log ("ending");
speed = defaultSpeed; // back to normal
renderer.material.color = Color.white;
audio.Stop (); //stops the Track 2
audio.clip = songs [0]; //Gets the Track 1
audio.Play (); //Plays Track 1
}
}
I call the function SpeedUp() by using this script(note that this script is the gameobject I grab): http://pastebin.com/8JxXvDan As for the EndSpeedUp() function, it's called 5 seconds after the SpeedUp function.
I know inefficient code, don't judge me. Anyways thanks for reading and your time.
hello,
maybe it would be relevant to see how you trigger those 2 functions.
You could remember the reference of the object you grabed and check if it as changed to know which clip to play .
"maybe it would be relevant to see how you trigger those 2 functions." Haha yeah I thought that before I posted this question, but I didn't think anyone would ask since most don't. I've updated my question, check it out when you have the time please.
"You could remember the reference of the object you grabed and check if it as changed to know which clip to play." I kinda understand what your talking about, but I'm unsure. I'll mess around and see if I can get it to work.
Answer by ironblock · Aug 05, 2014 at 07:36 AM
you just need an other check thats all somthing like
if ( speedUpSound == true )
{
/// change sount track here
speedIpSound = false;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Stuck on this! Please help me out. 1 Answer
Simple Timer 2 Answers
A node in a childnode? 1 Answer