- Bug场景:
在Unity运行情况正常(点击某个按钮,该按钮翻转)
而在打包运行时,点击某按钮,其他的其中一个按钮翻转。
- 原因:
多个按钮查找使用了通过标签查找:在Awark()中btns=GameObject.FindGameObjectsWithTag("Button");
翻转又用到了该数组btns[i]。
通过标签查找的数组顺序不固定。
- 解决:
使用其他方法获取按钮数组:
1.public Button[] btns;//直接将多个按钮拖拽
2.分别单独获取
3.欢迎补充(呜呜呜我不知道)
- 代码部分:
已删减,只作为思路提供。
public class GamePlay4 : MonoBehaviour
{
public GameObject[] buttons;//游戏按钮
/// <summary>
/// 洗牌(随机调换按钮位置)
/// </summary>
void ShuffleButtons()
{
random = new Random(); // 初始化随机数生成器
for (int i = 0; i < buttons.Length / 2; i++)
{
int randomIndex = random.Next(buttons.Length / 2, buttons.Length); // 生成一个随机索引
Vector3 temp = buttons[i].transform.position; // 临时存储当前按钮的位置
buttons[i].transform.position = buttons[randomIndex].transform.position; // 将随机索引处的按钮的位置放到当前位置
buttons[randomIndex].transform.position = temp; // 将当前位置处的按钮的位置放到随机索引处
}
}
private void GameStart()
{
palyGameBg.enabled = true;//游戏背景打开
//显示所有按钮
foreach (var button in buttons)
{
button.SetActive(true);
}
_playBtn.gameObject.SetActive(false);
videoImage.GetComponent<RawImage>().enabled = false;
isPlay = true;
ShuffleButtons(); // 洗牌(随机调换按钮位置)
}
//绑定到按钮
public void Button1()
{
string name = buttons[0].GetComponent<Image>().sprite.name.ToString();
buttons[0].GetComponent<Image>().sprite = errorImage;
StartCoroutine(WaitAndChangeImage(buttons[0], name));
}
IEnumerator WaitAndChangeImage(GameObject btn,string name)
{
// 等待指定的延迟时间后更换回原来图像
yield return new WaitForSeconds(delay);
btn.GetComponent<Image>().sprite = Resources.Load<Sprite>(name);
}
}