在Canvas上挂载脚本,把Canvas设定在最高层,在Canvas中根据顺序创建多个子物体当作每一步显示切换的提示框,在不同的提示框下创建名为btn的Button作为传递的点击事件,然后脚本中的Canvas公开拖拽此场景中其他需要传递点击事件的Canvas,auidoLenge为声音的个数,教程没有声音就赋值0
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class GameTeach : MonoBehaviour
{
public List<GameObject> Canvas;
private List<GameObject> tips = new List<GameObject>();
private Dictionary<GameObject, Button> btns = new Dictionary<GameObject, Button>();
private List<Action> actions = new List<Action>();
private int index = 0;
private List<AudioClip> clips;
private GameObject lastopen;
public int auidoLenge = 0;
// Start is called before the first frame update
private void Start()
{
if (PlayerPrefs.GetInt("Teach") == 0)
{
Teach();
}
}
void Teach()
{
clips = new List<AudioClip>();
for (int i = 0; i < auidoLenge; i++)
{
if (GameManager.Main.ischinese)
{
clips.Add(Resources.Load<AudioClip>("Audio/TeachCn/" + i));
}
else
{
clips.Add(Resources.Load<AudioClip>("Audio/TeachEn/" + i));
}
}
for (int i = 0; i < transform.childCount; i++)
{
tips.Add(transform.GetChild(i).gameObject);
}
Button btn;
foreach (GameObject tip in tips)
{
btn = tip.transform.Find("btn").GetComponent<Button>();
if (btn != null)
{
btns.Add(tip, btn);
}
}
actions.Add(() =>
{
Open(tips[0]);
btns[tips[0]].onClick.AddListener(() =>
{
Transmit(Canvas[0]);
Next();
});
});
actions.Add(() =>
{
Open(tips[1]);
btns[tips[1]].onClick.AddListener(() =>
{
Transmit(Canvas[1]);
Next();
});
});
actions[0]();
}
void Next()
{
index++;
if (index >= actions.Count)
{
Destroy(gameObject);
PlayerPrefs.SetInt("Teach", 1);
PlayerPrefs.Save();
return;
}
actions[index]();
}
void Open(GameObject g)
{
if (lastopen != null)
{
lastopen.SetActive(false);
}
lastopen = g;
lastopen.SetActive(true);
}
void Transmit(GameObject g)
{
try
{
GetCanvasTouch(g).GetComponent<Button>().onClick.Invoke();
}
catch (Exception e)
{
Debug.Log("传递点击事件出现错误,错误原因为:"+ e);
}
}
public GameObject GetCanvasTouch(GameObject canvas)
{
return GetCanvasTouch(canvas, GetNumPos());
}
private PointerEventData pointerEventData;
private GraphicRaycaster gr;
List<RaycastResult> results = new List<RaycastResult>();
public GameObject GetCanvasTouch(GameObject canvas , Vector2 vector2)
{
// if(!GetClickAlways()){return null;}
gr = canvas.transform.GetComponent<GraphicRaycaster>();
pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = vector2;
pointerEventData.pressPosition = vector2;
results.Clear();
gr.Raycast(pointerEventData, results);
if(results.Count>0){return results[0].gameObject;} return null;
}
public Vector3 GetNumPos()
{
if (SystemInfo.deviceType == DeviceType.Desktop)
{
return Input.mousePosition;
}
else
{
if (Input.touchCount > 0)
{
return Input.GetTouch(0).position;
}
else
{
return Vector3.zero;
}
}
}
}