[英]how do I make the sound in my script play only once?
我有个问题。 我有一个脚本,当玩家靠近带有脚本的游戏对象时,它会导致播放声音。 然而,只要玩家在那个范围内,播放声音的脚本就会被一遍又一遍地调用,所以声音一遍又一遍地播放,听起来都混杂在一起。 你能告诉我如何让我的脚本在再次播放之前等待声音完成吗? (不要关注 is player alive bool,那是为了别的东西)
这是我的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playSiren : MonoBehaviour
{
public AudioClip siren;
public Transform player;
public float playerDistance;
public static bool isPlayerAlive = true;
private AudioSource source;
// Start is called before the first frame update
void Start()
{
source = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (isPlayerAlive)
{
playerDistance = Vector3.Distance(player.position, transform.position);
if (playerDistance < 12f)
{
chase();
}
}
void chase()
{
source.PlayOneShot(siren);
}
}
}
您可以设置一个变量来确定是否需要调用chase
方法。 例如:
private bool isWithinDistance = false;
void Update ( )
{
if ( isPlayerAlive )
{
playerDistance = Vector3.Distance ( player.position, transform.position );
if ( !isWithinDistance && playerDistance < 12f )
{
isWithinDistance = true;
chase ( );
}
if ( isWithinDistance && playerDistance > 12f ) isWithinDistance = false;
}
void chase ( )
{
source.PlayOneShot ( siren );
}
}
请注意,您的chase
方法包含在Update
方法中。 这在较新版本的 C# 中是合法的,但这可能不是您想要的代码格式? 像这样的子方法只能从包含方法调用 - 在这种情况下很好 - 但你将无法从其他任何地方调用chase
。
而不是使用距离:使用 collider ,使其成为触发器(编辑器中的复选框),然后使用内置功能“ onTrigger something ”在输入或任何时候播放声音。 另一种方法是添加一个 bool 来判断声音是否开始播放。 除非 boll 为假,否则函数不会开始播放的另一个条件。 添加更新小 if 语句,如果此 bool 为真,则倒计时 1 秒并再次使其为假。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.