2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個贊
你只需要在播放音樂之前添加一個條件來檢查它是否已經(jīng)在播放。喜歡....
void Update()
{
if (Input.GetKey("up") == true || Input.GetKey("down") == true || Input.GetKey("left") == true || Input.GetKey("right") == true)
{
Drive();
if (!CarEngine.isPlaying)
CarEngine.Play();
}
else
{
if (CarEngine.isPlaying)
{
Debug.Log("Stop playing....");
CarEngine.Stop();
}
}
}

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個贊
首先,我看到有一些不必要的代碼行,我們將消除它們。
然后,我們創(chuàng)建了一個方法來使用一個布爾參數(shù)來重現(xiàn)聲音,該參數(shù)將用于重現(xiàn)或停止音頻,這個參數(shù)將是一個布爾值,那么只有當(dāng)該布爾值為真時才會拒絕音頻,所以你必須說它按下一個鍵時為真。
否則,如果您簡化工作,實(shí)際上您正在驗(yàn)證從第一個上面到最后一個 else 中的哪一個滿足,如果滿足則執(zhí)行第一行,否則執(zhí)行 else。
using UnityEngine;
public class RaceCarMovement : MonoBehaviour {
float drivespeed = 0.3f;
private AudioSource CarEngine;
private void Awake()
{
CarEngine = GetComponent<AudioSource>();
}
void Start ()
{
}
void Update()
{
if (Input.GetKey("up"))
{
transform.position = new Vector3(transform.position.x + drivespeed, transform.position.y);
PlayCarSound(true);
}
else if (Input.GetKey("down"))
{
transform.position = new Vector3(transform.position.x - drivespeed, transform.position.y);
PlayCarSound(true);
}
else if (Input.GetKey("left"))
{
transform.position = new Vector3(transform.position.x, transform.position.y + drivespeed);
PlayCarSound(true);
}
else if (Input.GetKey("right"))
{
transform.position = new Vector3(transform.position.x, transform.position.y - drivespeed);
PlayCarSound(true);
}
else
{
PlayCarSound(false);
}
}
private void PlayCarSound(bool play)
{
if(play /*&& !CarEngine.isPlaying*/) CarEngine.Play();
else CarEngine.Stop();
}
}
- 2 回答
- 0 關(guān)注
- 227 瀏覽
添加回答
舉報(bào)