Hello, I’m relatively new to C# and Unity. I’m thought I’d try and use Unity’s default 1st person Controller Script as a starting point and add in the ability to play the correct footstep audio for the correctly tagged surface in-game.
Below is where I’m at. I’m able to add elements to each of of the soundxxxxx fields but they don’t play audio. Any help would be greatly appreciated!
*These are just my alterations to the 1st person controller script rather than the whole code. Hope it’s enough.
using System;
using UnityEngine;
using System.Collections;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
[SerializeField] private AudioClip[] soundGround;
[SerializeField] private AudioClip[] soundWood;
[SerializeField] private AudioClip[] soundGrass;
[SerializeField] private AudioClip[] soundWater;
private AudioSource m_AudioSource;
private void Start()
{
m_AudioSource = GetComponent<AudioSource> ();
}
private IEnumerator PlayFootStepAudio()
{
while(true) {
float vel = m_CharacterController.velocity.magnitude;
RaycastHit hit = new RaycastHit();
string floortag;
if(m_CharacterController.isGrounded == true && vel > 0.2f) {
if(Physics.Raycast(transform.position, Vector3.down,out hit))
{
floortag = hit.collider.gameObject.tag;
if (floortag == "Ground")
{
m_AudioSource.clip = soundGround[Random.Range(0,soundGround.Length)];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
}
else if (floortag == "Wood")
{
m_AudioSource.clip = soundWood[Random.Range(0,soundWood.Length)];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
}
else if (floortag == "Grass")
{
m_AudioSource.clip = soundGrass[Random.Range(0,soundGrass.Length)];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
}
else if (floortag == "Water")
{
m_AudioSource.clip = soundWater[Random.Range(0,soundWater.Length)];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
}
}
}
else {
yield return 0;
}
}
}