다중 오디오 클립
다중으로 오디오 클립을 캐싱하여 조건마다 소리를 낼 수 있다.

CollisionHandler.cs
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionHandler : MonoBehaviour
{
private AudioSource _audioSource;
private Movement _movement;
[SerializeField] float levelLoadDelay = 1f;
[SerializeField] private AudioClip crashSound;
[SerializeField] private AudioClip landingSound;
private void Start()
{
_audioSource = GetComponent<AudioSource>();
_movement = GetComponent<Movement>();
}
private void OnCollisionEnter(Collision collision)
{
switch (collision.gameObject.tag)
{
case "Friendly":
Debug.Log("This thing is firendly");
break;
case "Finish":
StartSuccessSequence();
break;
default:
StartCrashSequence();
break;
}
}
void StartCrashSequence()
{
PlaySound(crashSound);
_movement.enabled = false;
Invoke(nameof(ReloadLevel), levelLoadDelay);
}
void LoadNextLevel()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = currentSceneIndex + 1;
if (nextSceneIndex == SceneManager.sceneCountInBuildSettings)
{
nextSceneIndex = 0;
}
SceneManager.LoadScene(nextSceneIndex);
}
void StartSuccessSequence()
{
PlaySound(landingSound);
_movement.enabled = false;
Invoke(nameof(LoadNextLevel), levelLoadDelay);
}
void ReloadLevel()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex);
}
void PlaySound(AudioClip clip)
{
GetComponent<AudioSource>().PlayOneShot(clip);
}
}
Movement.cs
using UnityEngine;
public class Movement : MonoBehaviour
{
private bool isAlive;
private Rigidbody _rigid;
private AudioSource _audioSource;
[SerializeField] private float mod = 100f;
[SerializeField] private float rotationSpeed = 1f;
[SerializeField] private AudioClip _mainEngine;
void Start()
{
_rigid = GetComponent<Rigidbody>();
_audioSource = GetComponent<AudioSource>();
}
void Update()
{
ProcessThrust();
ProcessRotation();
}
void ProcessThrust()
{
if (Input.GetKey(KeyCode.Space))
{
_rigid.AddRelativeForce(Vector3.up * (mod * Time.deltaTime));
if (!_audioSource.isPlaying)
_audioSource.PlayOneShot(_mainEngine);
}
else
_audioSource.Stop();
}
void ProcessRotation()
{
if (Input.GetKey(KeyCode.A))
{
ApplyRotation(rotationSpeed);
}
else if (Input.GetKey(KeyCode.D))
{
ApplyRotation(-rotationSpeed);
}
}
private void ApplyRotation(float rotationThisFrame)
{
// rigid.constraints = (RigidbodyConstraints)((int)RigidbodyConstraints.FreezeRotationX + (int)RigidbodyConstraints.FreezeRotationY);
// rigid.constraints = RigidbodyConstraints.FreezeRotation;
_rigid.freezeRotation = true;
transform.Rotate(Vector3.forward * (rotationThisFrame * Time.deltaTime));
_rigid.freezeRotation = false;
}
}
플레이 영상
착지 이후에 충돌 소리가 나는 버그는 나중에 수정하도록 하자 (collision 스크립트를 끈다던지)
'유데미 강의 > C#과 Unity로 3D 게임 개발하기 : 부스트 프로젝트' 카테고리의 다른 글
파티클 시스템 (0) | 2022.08.23 |
---|---|
bool 변수로 제어하기, 로켓 꾸미기 (0) | 2022.08.23 |
Invoke 함수 사용 (0) | 2022.08.12 |
SceneManager (0) | 2022.08.12 |
Switch (0) | 2022.08.12 |