Stopping Audio When Zoomed In/Out
Description So, I have got a camera zooming script in which when the user right click's the camera will zoom in, when they right click again the camera will zoom out and so on. But I want to have audio when the user zooms in/out, but I am having trouble coding it. So far the script will toggle a bool when the user right clicks which will tell the audio source to play, but when it reaches the desired values the sound does not stop, I cannot use the exact values as the Mathf.Lerp does quite get "60". Anyway here is the script.
Script
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
//Zoom Variables
private int zoom = 30;
private int normal = 59;
private float smooth = 5;
private bool isZoomed= false;
//Audio Variables
private AudioSource audio;
public bool AudioPlaying;
void Start()
{
audio = GetComponent<AudioSource> ();
}
//Function that is called every Frame
void Update ()
{
//If Right Click has been Pressed
if(Input.GetMouseButtonDown(1))
{
//Toggle the isZoomed Boolean
isZoomed = !isZoomed;
//Play the Zoom Sound
AudioPlaying = true;
}
//If the Camera is Zoomed
if(isZoomed == true)
{
//Set the FOV to 20
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth);
if (GetComponent<Camera> ().fieldOfView > 58)
{
Debug.Log ("Audio Stop");
AudioPlaying = false;
}
}
//If the Camera is not Zoomed
if(isZoomed == false)
{
//Set the FOV to 60
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth);
if (GetComponent<Camera> ().fieldOfView < 31)
{
Debug.Log ("Audio Stop");
AudioPlaying = false;
}
}
if (AudioPlaying == true)
{
Debug.Log ("Play Audio");
audio.Play();
}
if (AudioPlaying == false)
{
Debug.Log ("Stop Audio");
audio.Stop();
}
}
}
What do you see in the console? It looks like those debug.logs should tell you a lot.
The only thing I can see from the code alone is that you should really only call play() and stop() once, ins$$anonymous$$d of every frame like you are now. I would get rid of the bool, and actually call play and stop in those functions, when necessary.
Your answer
Follow this Question
Related Questions
Playing multiple audio clips 2 Answers
I can't get my sound to work! 1 Answer
Why won't my second Audio Source play? 0 Answers
oneshot not working 0 Answers
Is there a way to update the audioclip of an object pooled audiosource instance? 1 Answer