我有26个图像(GameObjects),每个图像都有一个按钮。 如果单击按钮,它将播放声音和动画。
但是,我有一个问题。我试图防止这种情况,但是如果执行多点触摸/压力测试,某些按钮将无法再单击。如果我单击缓慢,则效果很好,但是如果我对某个按钮执行多次单击,则它将失败/无法再单击。知道为什么吗?
我的源代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DG.Tweening;
[RequireComponent(typeof(AudioSource))]
public class z_abcLetter_Main : MonoBehaviour {
public GameObject InputData;
public List<GameObject> List_uGUI;
private List<Sprite> List_Sprite;
private List<AudioClip> List_AudioClip;
private int currentIndex;
private GameObject currentGameObject;
private GameObject parentGameObject;
// Use this for initialization
void Start () {
List_Sprite = InputData.GetComponent<z_abcLetter_InputData>().Daftar_element;
List_AudioClip = InputData.GetComponent<z_abcLetter_InputData>().Daftar_Suara;
int total_element = List_Sprite.Count;
for (int i = 0; i < total_element; i++)
{
List_uGUI[i].GetComponent<UnityEngine.UI.Image>().sprite = List_Sprite[i];
List_uGUI[i].GetComponent<UnityEngine.UI.Image>().preserveAspect = true;
}
}
public void onButtonClick()
{
currentIndex = int.Parse(EventSystem.current.currentSelectedGameObject.transform.parent.name.ToString());
currentGameObject = EventSystem.current.currentSelectedGameObject;
parentGameObject = currentGameObject.transform.parent.gameObject;
StartCoroutine(PlaySoundWithAnimation());
}
IEnumerator PlaySoundWithAnimation()
{
currentGameObject.GetComponent<UnityEngine.UI.Button>().enabled = false;
currentGameObject.GetComponent<UnityEngine.UI.Button>().interactable = false;
AudioSource audio = GetComponent<AudioSource>();
audio.clip = List_AudioClip[currentIndex];
audio.Play();
parentGameObject.transform.DOPunchScale(new Vector3(2, 2, 0), 1, 1, 1);
yield return new WaitForSeconds(1.5f);
currentGameObject.GetComponent<UnityEngine.UI.Button>().enabled = true;
currentGameObject.GetComponent<UnityEngine.UI.Button>().interactable = true;
}
// Update is called once per frame
void Update () {
}
}
答案 0 :(得分:1)
您的代码似乎表现出预期的效果。但是要获得快速的多次点击,您需要重置协程。
为此,您需要引用PlaySoundWithAnimation。
private IEnumerator coroutine;
void Start()
{
coroutine = PlaySoundWithAnimation();
}
public void onButtonClick()
{
StopCoroutine(coroutine);
// you also need to stop audio here
//...
StartCoroutine(coroutine);
}
请参阅:https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
某些按钮不响应的原因是协程已堆叠,它们都在等待yield return new WaitForSeconds(1.5f);
请参阅:https://answers.unity.com/questions/309613/calling-startcoroutine-multiple-times-seems-to-sta.html
注意:
如果您不想停止剪辑,请在启用按钮之前考虑audio.clip.length
。