zl程序教程

您现在的位置是:首页 >  工具

当前栏目

VR开发-按钮实现答题篇

VR开发 实现 按钮 答题
2023-09-27 14:27:29 时间

一、按钮实现答题功能

1、导入pico的SDK,建立一个Canvas,用作存放所有题目的面板,设置如图两处:①修改Canvas的空间和事件相机②挂上PICO的SDK中的UI交互脚本

在后面创建的每一个题目的Canvas将自动继承父亲Canvas的脚本,所以字Canvas上面都不需要做出这两项改变了

2、创建题目的Canvas,挂上脚本组件和Image(存放题目图片)组件

 代码脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AnswerManager : MonoBehaviour
{
    public GameObject CorrectShow;//存放下一个按钮
    public int RightKey;                  //正确答案下标
    public List<Button> KeyButtons;       //答案集合
    public static bool answerEnd = false;//修改:答题结束标志
    public GameObject endButton; //结束观看按钮

    void Start()
    {
        AddAnswer();//增加绑定此题的三个按钮的按钮函数
    }
    //答题选择
    public void SelectEvent(int index)
    {
        if (RightKey == index)                 //答对事件
        {
            //不需要显示图片KeyButtons[index].transform.parent.GetComponent<Image>().enabled = false;//按钮图片消失
            StartCoroutine(Answer());

        }
        else                                    //答错事件
        {
            KeyButtons[index].onClick.RemoveAllListeners(); //移除所按按钮的按钮函数
            StartCoroutine(Answerlost(KeyButtons[index].transform.parent.gameObject, index));//然后重新添加此按钮的按钮函数
        }
    }
    //给按钮绑定事件,第一题的第一个按钮绑定的参数为0,第二个按钮绑定为1.....
    public void AddAnswer()                 
    {
        KeyButtons[0].onClick.AddListener(delegate
        {
            SelectEvent(0);
        });
        KeyButtons[1].onClick.AddListener(delegate
        {
            SelectEvent(1);
        });
        KeyButtons[2].onClick.AddListener(delegate
        {
            SelectEvent(2);
        });
    }
    IEnumerator Answerlost(GameObject obj, int n)//答案ui关闭
    {
        yield return new WaitForSeconds(0.1f);
        //重新增加按钮函数
        obj.GetComponentInChildren<Button>().onClick.AddListener(delegate
        {
            SelectEvent(n);
        });
    }
    IEnumerator Answer() //答对,全部消失事件         
    {
        for (int i = 0; i < KeyButtons.Count; i++)
        {
            KeyButtons[i].enabled = false;//设置按钮不可见
        }
        yield return new WaitForSeconds(2f);
       
        for (int i = 0; i < KeyButtons.Count; i++)//所有按钮的父物体不可见
        {
            KeyButtons[i].transform.parent.gameObject.SetActive(false);
        }   

        //this.gameObject.SetActive(false);//将上面注释更改为下面
        if (CorrectShow != null)//如果下一个按钮不为null,则显示
        {
            CorrectShow.SetActive(true);
        }
        else//如果没有了下一个按钮就销毁预制体,显示结束按钮
        {
            answerEnd = true;
            this.gameObject.GetComponent<Image>().enabled = false;
            yield return new WaitForSeconds(2f);
            endButton.SetActive(true);
        }
        this.gameObject.SetActive(false); 
    }
}

3、题目选项组件

 Image父组件上面添加Image组件,添加透明图片

 Image子组件中,添加Image(存放选项的图片)组件和按钮组件,其中按钮组件改变转化的方式,选中为如图所示,增加选中和点击时的效果。