我对 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() 应该更新每一帧。有没有人有任何建议/解释?
噜噜哒
跃然一笑
相关分类