AudioClip not playing
I have an audio clip that I'm trying to have start when a certain condition is met. The clip is being attached through the script I'm running which is supposed to be played using the AudioSource
component attached to the GameObject
. The clip is not playing, however. The variable holding the clip is a public AudioClip
and it is being set within the inspector. Setting the AudioSource
to play on awake would work at this point, but would not at a later time, so I want to avoid doing that. Does anyone have any suggestions?
C#
using UnityEngine;
using System.Collections;
public class MoveCar:MonoBehaviour{
//Car's idle speed
private int idleSpeed = 0;
//Car's current speed
private float speed = 0.0f;
//Car's top speed
public float topSpeed = 165.0f;
//Car's acceleration rate
public float acceleration;
//Car's braking power
public float deceleration = 15f;
private Rigidbody playerCar;
private AudioSource engine;
public AudioClip carStartAudio;
private bool starting;
void Start(){
playerCar = GetComponent<Rigidbody>();
engine = playerCar.GetComponent<AudioSource>();
starting = true;
if(starting){
engine.clip = carStartAudio;
if(!engine.isPlaying){
engine.Play();
}
Debug.Log(engine.clip);
}
}
void Update(){
if(Input.GetKey(KeyCode.W)){
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if(speed <= topSpeed){
speed = speed + (acceleration * Time.deltaTime);
Vector3 movement = new Vector3(vertical, 0f, horizontal);
playerCar.AddForce(movement * Mathf.Clamp(speed, idleSpeed, topSpeed));
Debug.Log(speed);
}
else{
speed = topSpeed;
if(speed == topSpeed){
}
}
}
}
}
If anyone would like to actually see what's going on, I've uploaded the game to my Dropbox, feel free to take a look.
First of all i would suggest you assign your audioclips directly to the array in the inspector. But thats not the main problem here.
Have you already checked (use a debug) if your audioclip variables get assigned correctly? Do you get any errors? Also, do you really want to play the sound each single frame? $$anonymous$$abye calling the source each frame cancels the sound it started playing in the privious frame... just an idea.
Anyways: Please return wirh more info.
@Brullix3000 Sorry it took so long to get back to you. I have the audioclips assigned in the inspector and I am checking to see if they are being assigned correctly, they are. I also made the decision to focus on just one clip which should be playing in the start function, but isn't. I've made some changes to the project and the script and am updating my question to reflect that as well as added more details. I've also uploaded the game to my Dropbox so if you want to actually see what is actually happening, you're more than welcome to it.