- Home /
Sound Problem
Hi everyone I'm trying to get a walking sound to play when you move with the game. I tried a lot of methods and the simple audio.clip=walkSound and audio.Play, and non of that worked. Any ideas on how to make the sound play?
public float walkSpeed = 5.0f;
public float slowPentaly = 0.5f;
public float gravity = 20.0f;
public float run = 2.0f;
private Vector3 moveDirection = Vector3.zero;
public AudioClip walkSound;
void Start()
{
//transform.position = new Vector3(0,1.7f,0);
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.gameObject.tag == "Shard") {
moveDirection *= slowPentaly;
Debug.Log("You are slow");
}
}
void Update()
{
CharacterController controller = GetComponent<CharacterController> ();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
moveDirection = transform.TransformDirection (moveDirection);
moveDirection *= walkSpeed;
if (Input.GetKeyDown(KeyCode.LeftShift))
moveDirection *= run;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move (moveDirection * Time.deltaTime);
}
}
Answer by YoungDeveloper · Dec 29, 2014 at 09:14 PM
You can always use AudioSource.PlayClipAtPoint() http://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html Which will instantiate empty gameObject on it with audio source component with you clip attached, will play automatically and destroy when finished.
If the sound is 3d you might not hear if it's far away - isn't positioned correctly.
If you are using mecanim you can set animation events and exclude manual step counting.
To play the clip you need AudioSource, assign in via inspector or via code source.clip = yourClip, when you want to source.Play();.
If you still cant figure it out try it without updates and try triggering the sound from Start().
Ok so the AudioSource.PlayClipAtPoint plays the sound but it doesnt play right when I move the player. Either the sound keeps looping itself if I put it in the Update function or it plays once in the Start function. Any suggestions??
It's really impossible to tell without the context and this code. For character controller you should check if isGrounded => activate step counter. You could use coroutine as a separate handler for that.
This is just a quick sketch.
CharacterController controller;
bool playerDead = false;
void Start(){
controller = GetComponent<CharacterController> ();
StartCoroutine(StepsHandler());
}
IEnumerator StepsHandler(){
float timer = 1f;
while(!playerDead){
if(timer <= 0 && controller.isGrounded){
Debug.Log("sound");
timer = 1f;
}
else {timer -= Time.deltaTime;}
yield return null;
}
}
Your answer
Follow this Question
Related Questions
Character Movement and Jumping Script? 4 Answers
Walking Motion 1 Answer
[Help] How to prevent sound repeating (in this script) 3 Answers
How to play sound when object stops moving? 1 Answer
Walking using 2 buttons alternately 1 Answer