Unity Disorted Audio

我在Unity中播放音频剪辑时遇到问题。

当发现播放器但声音失真时,我希望我的鲨鱼产生“咬”声。

其余代码按预期运行。

我可以提供代码审查和建议吗?

我可能做错了什么(在调用音频源播放时)?

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shark2Controller : MonoBehaviour { public Transform leftPoint; public Transform rightPoint; public float startSpeed; public float swimSpeed; private Rigidbody2D myRigidBody; public bool swimmingRight; public float superSpeed; public Transform puntoA; public Transform puntoB; public LayerMask whatIsPlayer; public bool playerDetected; private Animator myAnim; public AudioSource bite; // Use this for initialization void Start () { myRigidBody = GetComponent (); myAnim = GetComponent(); swimSpeed = startSpeed; } // Update is called once per frame void Update () { playerDetected = Physics2D.OverlapArea (puntoA.position, puntoB.position, whatIsPlayer); myAnim.SetBool ("Player Detected", playerDetected); if (playerDetected) { swimSpeed = superSpeed; bite.Play (); } if (swimmingRight && transform.position.x > rightPoint.position.x) { swimmingRight = false; } if (!swimmingRight && transform.position.x < leftPoint.position.x) { swimmingRight = true; } if (swimmingRight) { myRigidBody.velocity = new Vector3 (swimSpeed, myRigidBody.velocity.y, 0f); transform.localScale = new Vector3 (1f, 1f, 1f); } else { myRigidBody.velocity = new Vector3 (-swimSpeed, myRigidBody.velocity.y, 0f); transform.localScale = new Vector3 (-1f, 1f, 1f); } } public void ResetShark2Speed() { swimSpeed = startSpeed; } } 

我看到的一个问题是,您在每次更新屏幕时都会重新播放声音 (基于应用程序的帧速率)。 目前尚不清楚你是否希望它循环(因为它被放置在一个void Update函数中,用于重复指令),或者你只是想让它在每次检测时播放一次。

如果Unity可以检测到声音正在播放或已完成,请使用它来帮助解决此问题。

循环逻辑是:

  • 在每次帧更新时,检查声音是否已处于“播放”模式。
  • 如果否…假设声音“结束”,你现在可以做bite.Play();
  • 否则 – 如果是……让声音继续(也许它将在未来的帧检查中“结束”)。

一个伪代码示例:

 if (playerDetected == true) { swimSpeed = superSpeed; if( bite.isPlaying == true) { //# Do nothing or whatever you need } else { //# Asssume it's not playing (eg: stopped, ended, not started, etc) bite.Play (); } } 

每次检测一次:

 public bool detect_snd_Played; detect_Snd_Played = false; //# Not yet played since no "detect" //# Update is called once per frame void Update () { if (playerDetected == true) { swimSpeed = superSpeed; } if (detect_Snd_Played == false) { bite.Play (); detect_Snd_Played = true; //# Stops future playback until you reset to false } } 

这行detect_Snd_Played = true; 应该停止多次播放,直到你重置。 这可能是因为你的玩家被鲨鱼“未检测到”,你现在可以重置为下一次新的“检测”过程……