In Day 15, we’re going to continue adding more sound effects to our existing game, specifically the:
shooting sound effect
sound of the knight getting hit
player walking
Today’s going to be a relatively short day, but get started!
Adding Enemy Hit Sounds
To start off, we’re going to do something like in Day 14. We’re going to create Audio Source Components in code and play the sound effects from there.
For shooting we need to add our code to EnemyHealth:
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float Health = 100;
public AudioClip[] HitSfxClips;
public float HitSoundDelay = 0.5f;
private Animator _animator;
private AudioSource _audioSource;
private float _hitTime;
void Start()
{
_animator = GetComponent<Animator>();
_hitTime = 0f;
SetupSound();
}
void Update()
{
_hitTime += Time.deltaTime;
}
public void TakeDamage(float damage)
{
if (Health <= 0) { return; } Health -= damage; if (_hitTime > HitSoundDelay)
{
PlayRandomHit();
_hitTime = 0;
}
if (Health <= 0)
{
Death();
}
}
private void SetupSound()
{
_audioSource = gameObject.AddComponent<AudioSource>();
_audioSource.volume = 0.2f;
}
private void PlayRandomHit()
{
int index = Random.Range(0, HitSfxClips.Length);
_audioSource.clip = HitSfxClips[index];
_audioSource.Play();
}
private void Death()
{
_animator.SetTrigger("Death");
}
}
The flow of new our code is:
We create our Audio Source component in SetupSound() called from Start()
We don’t want to play the sound of the knight being hit every time we hit it, that’s why I set a _hitTime in Update() as a delay for the sound
Whenever an enemy take damage, we see if we’re still in a delay for our hit, if we’re not, we’ll play a random sound clip we added.
The code above should seem relatively familiar as we seen it before in Day 14.
Once we have the code setup, the only thing left to do is to add the Audio clips that we want to use, which in this case is Male_Hurt_01 — Male_Hurt_04
That’s about it. If we were shoot the enemy now, they would make damage hits.
Player Shooting Sounds
The next sound effect that we want to add is the sound of our shooting. To do that, we’re going to make similar adjustments to the PlayerShootingController.
using UnityEngine;
public class PlayerShootingController : MonoBehaviour
{
public float Range = 100;
public float ShootingDelay = 0.1f;
public AudioClip ShotSfxClips;
private Camera _camera;
private ParticleSystem _particle;
private LayerMask _shootableMask;
private float _timer;
private AudioSource _audioSource;
void Start () {
_camera = Camera.main;
_particle = GetComponentInChildren<ParticleSystem>();
Cursor.lockState = CursorLockMode.Locked;
_shootableMask = LayerMask.GetMask("Shootable");
_timer = 0;
SetupSound();
}
void Update ()
{
_timer += Time.deltaTime;
if (Input.GetMouseButton(0) && _timer >= ShootingDelay)
{
Shoot();
}
else if (!Input.GetMouseButton(0))
{
_audioSource.Stop();
}
}
private void Shoot()
{
_timer = 0;
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
_audioSource.Play();
if (Physics.Raycast(ray, out hit, Range, _shootableMask))
{
print("hit " + hit.collider.gameObject);
_particle.Play();
EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
if (enemyMovement != null)
{
enemyMovement.KnockBack();
}
if (health != null)
{
health.TakeDamage(1);
}
}
}
private void SetupSound()
{
_audioSource = gameObject.AddComponent<AudioSource>();
_audioSource.volume = 0.2f;
_audioSource.clip = ShotSfxClips;
}
}
The flow of the code is like the previous ones, however for our gun, I decided that I want to use the machine gun sound instead of individual pistol shooting.
We still setup our Audio Component code in Start()
The interesting part is that in Update(), we play our Audio in Shoot() and as long as we’re holding down the mouse button, we’ll continue playing the shooting sound and when we let go, we would stop the audio
After we added our script, we attach Machine_Gunfire_01 to the script component.
Player Walking Sound
Last but not least, we’re going to add the player walking sound in our PlayerController component.
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float Speed = 3f;
public AudioClip[] WalkingClips;
public float WalkingDelay = 0.3f;
private Vector3 _movement;
private Rigidbody _playerRigidBody;
private AudioSource _walkingAudioSource;
private float _timer;
private void Awake()
{
_playerRigidBody = GetComponent<Rigidbody>();
_timer = 0f;
SetupSound();
}
private void SetupSound()
{
_walkingAudioSource = gameObject.AddComponent<AudioSource>();
_walkingAudioSource.volume = 0.8f;
}
private void FixedUpdate()
{
_timer += Time.deltaTime;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if (horizontal != 0f || vertical != 0f)
{
Move(horizontal, vertical);
}
}
private void Move(float horizontal, float vertical)
{
if (_timer >= WalkingDelay)
{
PlayRandomFootstep();
_timer = 0f;
}
_movement = (vertical * transform.forward) + (horizontal* transform.right);
_movement = _movement.normalized * Speed * Time.deltaTime;
_playerRigidBody.MovePosition(transform.position + _movement);
}
private void PlayRandomFootstep()
{
int index = Random.Range(0, WalkingClips.Length);
_walkingAudioSource.clip = WalkingClips[index];
_walkingAudioSource.Play();
}
}
Explanation
This code is like what we’ve seen before, but there were some changes made.
Like usual, we create the sound component in Start() and a walking sound delay
In Update(), we made some changes. We don’t want play our walking sound whenever we can. We only want to play it when we’re walking. To do this, I added a check to see if we’re moving before playing our sound in Move()
Also notice that the audio sound is 0.8 as oppose to our other sounds. We want our sound to be louder than the other players so we can tell the difference between the player walking and the enemy.
After writing the script, we don’t forget to add the sound clips. In this case, I just re-used our footsteps by using Footstep01 — Footstep04
Conclusion
I’m going to call it quits for today for Day 15!
Today we added more gameplay sound into the game so when we play, we have a more complete experience.
I’m concerned about what happens when we have more enemies and how that would affect the game, but that’ll be for a different day!
Original Day 15.
Visit the 100 Days of Unity VR Development main page.
Visit our Homepage
↧