I have the script for the footstep sound, modified to work with the mobile FPS controller.
I am trying to use raycast to detect the floor below player and play different sound for the same.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(CharacterController))]
public class footsteps1: MonoBehaviour {
public AudioClip soundCarpet;
public AudioClip soundOut;
public AudioClip soundWater;
public AudioClip soundMetal;
private CharacterController _controller;
void Awake() {
_controller = GetComponent<CharacterController>();
}
// Use this for initialization
IEnumerator Start () {
while(true) {
float vel = _controller.velocity.magnitude;
if(_controller.isGrounded == true && vel > 0.2f) {
if(Physics.Raycast(transform.position, Vector3.down,out hit))
{
//Detect the floor and save its tag
}
//audio.clip = sounds[Random.Range(0, sounds.Length)];
//Debug.Log("sound");
//audio.PlayOneShot(audio.clip);
//float interval = audio.clip.length;
yield return new WaitForSeconds(interval);
}
else {
yield return 0;
}
}
}
}
3 Answers
3
getting something to work by yourself is kind of best feeling in the world
anyway for anyone wanting the footstep script here it is, put it on your fps character
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(CharacterController))]
public class footsteps1: MonoBehaviour {
public AudioClip[] soundCarpet;
public AudioClip[] soundOut;
public AudioClip[] soundWater;
public AudioClip[] soundMetal;
private CharacterController _controller;
void Awake() {
_controller = GetComponent<CharacterController>();
}
// Use this for initialization
IEnumerator Start () {
while(true) {
float vel = _controller.velocity.magnitude;
RaycastHit hit = new RaycastHit();
string floortag;
if(_controller.isGrounded == true && vel > 0.2f) {
if(Physics.Raycast(transform.position, Vector3.down,out hit))
{
floortag = hit.collider.gameObject.tag;
if (floortag == "carpet")
{
audio.clip = soundCarpet[Random.Range(0,soundCarpet.Length)];
}
else if (floortag == "out")
{
audio.clip = soundOut[Random.Range(0,soundOut.Length)];
}
else if (floortag == "water")
{
audio.clip = soundWater[Random.Range(0,soundWater.Length)];
}
else if (floortag == "metal")
{
audio.clip = soundMetal[Random.Range(0,soundMetal.Length)];
}
}
//audio.clip = sounds[Random.Range(0, sounds.Length)];
Debug.Log("sound");
audio.PlayOneShot(audio.clip);
float interval = audio.clip.length;
yield return new WaitForSeconds(interval);
}
else {
yield return 0;
}
}
}
}
@yusolaifdfer Nicely done. 
Hey, I have one problem with the script. When I tried to add the script to my Player, it told me the following: “Can’t add script behavior Footsteps. The scripts file name does not match the name of the class defined in the script”. I’m new to programming in Unity, and I don’t know what to do.
Could anybody help me find out whats wrong?
just tell me how to use the raycasting !
– yusolaifdfer