我是C#的新手,几天前我刚开始使用Unity。我正在尝试设置一个脚本,当赛车行驶时,您会听到引擎的声音,但是如果赛车停止了,您就不会听到引擎的声音。但是,当汽车停止行驶时,我一直无法使音频停止播放。这是程序:
using UnityEngine;
public class RaceCarMovement : MonoBehaviour {
// Use this for initialization
float drivespeed = 0.3f;
private AudioSource CarEngine;
private void Awake()
{
CarEngine = GetComponent<AudioSource>();
}
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("up") == true || Input.GetKey("down") == true || Input.GetKey("left") == true || Input.GetKey("right") == true)
{
Drive();
CarEngine.Play();
}
else
{
if (CarEngine.isPlaying)
{
CarEngine.Stop();
}
}
}
public void Drive()
{
if (Input.GetKey("up") == true)
{
transform.position = new Vector3(transform.position.x + drivespeed, transform.position.y);
}
if (Input.GetKey("down") == true)
{
transform.position = new Vector3(transform.position.x - drivespeed, transform.position.y);
}
if (Input.GetKey("left") == true)
{
transform.position = new Vector3(transform.position.x, transform.position.y + drivespeed);
}
if (Input.GetKey("right") == true)
{
transform.position = new Vector3(transform.position.x, transform.position.y - drivespeed);
}
}
}
我不明白else语句如何工作,因为Update()应该更新每一帧。有人有任何建议/解释吗?
答案 0 :(得分:1)
您只需要在播放音乐之前添加一个条件,以检查它是否已经在播放。喜欢......
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();
}
}
}
答案 1 :(得分:1)
首先,我看到有一些不必要的代码行,我们将消除它们。
然后,我们创建一个使用布尔参数来再现声音的方法,该参数将用于再现或停止音频,此参数将是布尔值,那么当该布尔值为true时,仅音频会被拒绝,因此您必须说这是真的,同时按下一个键。
否则,如果您简化了工作,实际上您是在验证从第一个(如果向下)到最后一个(其他)之间是否满足所有条件,并执行第一行(如果已满足),否则将执行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();
}
}