Skip to content

Instantly share code, notes, and snippets.

@nkjzm
Created October 30, 2019 15:50
Show Gist options
  • Save nkjzm/1cadb94fe5ea4248ecb3f0b1534202cf to your computer and use it in GitHub Desktop.
Save nkjzm/1cadb94fe5ea4248ecb3f0b1534202cf to your computer and use it in GitHub Desktop.
【Unity】クリック座標を指定してButton/ToggleのOnPointerClick()を発火させる【TestRunner】
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using UnityEngine.SceneManagement;
public class ClickTest
{
[SetUp]
public void SetUp()
{
SceneManager.LoadScene("Main");
}
[UnityTest]
public IEnumerator TestWithEnumeratorPasses()
{
Click(170, 520);
Assert.True(GameObject.FindObjectOfType<Toggle>().isOn);
yield return null;
}
void Click(int x, int y)
{
// ポインタイベントの作成
var ev = new PointerEventData(EventSystem.current);
ev.position = new Vector2(x, y);
// EventSystem経由でクリック結果を取得
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(ev, results);
var target = results.Select(r => r.gameObject).First(t => t != null);
// 階層を辿ってクリックイベントを発火
ExecuteClickHierarchy(target, ev);
}
static void ExecuteClickHierarchy(GameObject root, BaseEventData eventData)
{
var transformList = new List<Transform>();
GetEventChain(root, transformList);
for (var i = 0; i < transformList.Count; i++)
{
var transform = transformList[i];
ExecuteEvents.EventFunction<IPointerClickHandler> callback = (handler, ev) =>
{
handler.OnPointerClick((PointerEventData)ev);
};
if (ExecuteEvents.Execute<IPointerClickHandler>(transform.gameObject, eventData, callback))
{
return;
}
}
Debug.LogError("クリック失敗");
}
static void GetEventChain(GameObject root, IList<Transform> eventChain)
{
if (root == null) { return; }
var t = root.transform;
while (t != null)
{
eventChain.Add(t);
t = t.parent;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment