This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,114 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
internal class GraphicRaycasterButtonTests
{
Camera m_Camera;
EventSystem m_EventSystem;
Canvas m_Canvas;
Button m_ParentButton;
Button m_ChildButton;
Sprite m_Sprite;
const int TextureSize = 64;
readonly Texture2D texture = new Texture2D(TextureSize, TextureSize);
[UnitySetUp]
public IEnumerator TestSetup()
{
m_Camera = new GameObject("Camera").AddComponent<Camera>();
m_Camera.transform.position = new Vector3(0, 0, -10);
m_Canvas = new GameObject("Canvas").AddComponent<Canvas>();
m_Canvas.renderMode = RenderMode.ScreenSpaceOverlay;
m_Canvas.gameObject.AddComponent<GraphicRaycaster>();
m_EventSystem = new GameObject("Event System").AddComponent<EventSystem>();
Color[] colors = new Color[TextureSize * TextureSize];
for (int y = 24; y < 40; y++)
for (int x = 0; x < TextureSize; x++)
colors[y + TextureSize * x] = colors[x + TextureSize * y] = Color.red;
texture.SetPixels(colors);
texture.Apply();
m_Sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100);
var parentImage = new GameObject("ParentButton", typeof(RectTransform)).AddComponent<Image>();
parentImage.transform.SetParent(m_Canvas.transform);
parentImage.rectTransform.anchoredPosition = new Vector2(0, 0);
parentImage.sprite = m_Sprite;
parentImage.SetNativeSize();
m_ParentButton = parentImage.gameObject.AddComponent<Button>();
// Duplicate Button as a child GO
m_ChildButton = Object.Instantiate(m_ParentButton, m_ParentButton.transform);
m_ChildButton.name = "ChildButton";
var childImage = m_ChildButton.GetComponent<Image>();
childImage.rectTransform.anchoredPosition = new Vector2(8, 50);
parentImage.alphaHitTestMinimumThreshold = 0.5f;
childImage.alphaHitTestMinimumThreshold = 0.5f;
// Yield one frame so that all tests below work.
yield return null;
}
[Test]
[TestCase( 0f, -40f, false, false, TestName = "Should not hit either button (outside of both boundaries)")]
[TestCase( 0f, 0f, true, false, TestName = "Should hit the parent (opaque pixel), but not the child (outside)")]
[TestCase(-30f, -30f, false, false, TestName = "Should not hit the parent (transparent pixel), nor the child (outside)")]
[TestCase( 10f, 30f, false, true, TestName = "Should not hit the parent (transparent pixel), but hit the child (opaque pixel),")]
[TestCase( 5f, 30f, true, true, TestName = "Should hit the parent (opaque pixel), and the child (opaque pixel)")]
[TestCase( -5f, 30f, true, false, TestName = "Should hit the parent (opaque pixel), but not the child (transparent pixel)")]
[TestCase(-10f, 30f, false, false, TestName = "Should not hit the parent (transparent pixel), nor the child (transparent pixel)")]
[TestCase( 8f, 50f, false, true, TestName = "Should not hit the parent (outside), but hit the child (opaque pixel)")]
[TestCase(-10f, 30f, false, false, TestName = "Should not hit the parent (outside), nor the child (transparent pixel)")]
public void GraphicRaycaster_ChildButtonOutsideOfParentButton(float x, float y, bool hitParent, bool hitChild)
{
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f + x, Screen.height / 2f + y)
};
m_EventSystem.RaycastAll(pointerEvent, results);
if (hitParent == false && hitChild == false)
{
Assert.IsEmpty(results, "Expected no results from a raycast.");
}
else
{
if (hitParent && hitChild)
Assert.AreEqual(2, results.Count, "Expected 2 results from a raycast.");
else
Assert.AreEqual(1, results.Count, "Expected 1 result from a raycast.");
int hitIndex = 0;
if (hitChild)
{
Assert.AreSame(m_ChildButton.gameObject, results[hitIndex].gameObject);
hitIndex++;
}
if (hitParent)
{
Assert.AreSame(m_ParentButton.gameObject, results[hitIndex].gameObject);
}
}
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_Camera.gameObject);
Object.DestroyImmediate(m_EventSystem.gameObject);
Object.DestroyImmediate(m_Canvas.gameObject);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 53ee1d135588bf447a7af7ba2e8709d7
@@ -0,0 +1,151 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine.TestTools.Utils;
internal class GraphicRaycasterTests
{
Camera m_Camera;
EventSystem m_EventSystem;
Canvas m_Canvas;
RectTransform m_CanvasRectTrans;
Text m_TextComponent;
[SetUp]
public void TestSetup()
{
m_Camera = new GameObject("GraphicRaycaster Camera").AddComponent<Camera>();
m_Camera.transform.position = Vector3.zero;
m_Camera.transform.LookAt(Vector3.forward);
m_Camera.farClipPlane = 10;
m_EventSystem = new GameObject("Event System").AddComponent<EventSystem>();
m_Canvas = new GameObject("Canvas").AddComponent<Canvas>();
m_Canvas.renderMode = RenderMode.WorldSpace;
m_Canvas.worldCamera = m_Camera;
m_Canvas.gameObject.AddComponent<GraphicRaycaster>();
m_CanvasRectTrans = m_Canvas.GetComponent<RectTransform>();
m_CanvasRectTrans.sizeDelta = new Vector2(100, 100);
var textGO = new GameObject("Text");
m_TextComponent = textGO.AddComponent<Text>();
var textRectTrans = m_TextComponent.rectTransform;
textRectTrans.SetParent(m_Canvas.transform);
textRectTrans.anchorMin = Vector2.zero;
textRectTrans.anchorMax = Vector2.one;
textRectTrans.offsetMin = Vector2.zero;
textRectTrans.offsetMax = Vector2.zero;
}
[UnityTest]
public IEnumerator GraphicRaycasterDoesNotHitGraphicBehindCameraFarClipPlane()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
Assert.IsEmpty(results, "Expected no results from a raycast against a graphic behind the camera's far clip plane.");
}
[UnityTest]
public IEnumerator GraphicRaycasterReturnsWorldPositionAndWorldNormal()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
m_Camera.farClipPlane = 12;
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
// on katana on 10.13 agents world position returned is 0, -0.00952, 11
// it does not reproduce for me localy, so we just tweak the comparison threshold
Assert.That(new Vector3(0, 0, 11), Is.EqualTo(results[0].worldPosition).Using(new Vector3EqualityComparer(0.01f)));
Assert.That(new Vector3(0, 0, -1), Is.EqualTo(results[0].worldNormal).Using(new Vector3EqualityComparer(0.001f)));
}
[UnityTest]
public IEnumerator GraphicRaycasterUsesGraphicPadding()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
m_TextComponent.raycastPadding = new Vector4(-50, -50, -50, -50);
m_Camera.farClipPlane = 12;
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2((Screen.width / 2f) - 60, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
Assert.IsNotEmpty(results, "Expected at least 1 result from a raycast outside the graphics RectTransform whose padding would make the click hit.");
}
[UnityTest]
public IEnumerator GraphicOnTheSamePlaneAsTheCameraCanBeTargetedForEvents()
{
m_Canvas.renderMode = RenderMode.ScreenSpaceCamera;
m_Canvas.planeDistance = 0;
m_Camera.orthographic = true;
m_Camera.orthographicSize = 1;
m_Camera.nearClipPlane = 0;
m_Camera.farClipPlane = 12;
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2((Screen.width / 2f), Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
Assert.IsNotEmpty(results, "Expected at least 1 result from a raycast ");
}
#if ENABLE_INPUT_SYSTEM && PACKAGE_INPUTSYSTEM
[UnityTest]
public IEnumerator GraphicRaycasterIgnoresEventsFromTheWrongDisplay()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
m_Camera.farClipPlane = 12;
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f),
displayIndex = 1,
};
m_EventSystem.RaycastAll(pointerEvent, results);
Assert.IsEmpty(results, "Pointer event on display 1 was not ignored on display 0");
}
#endif
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_Camera.gameObject);
Object.DestroyImmediate(m_EventSystem.gameObject);
Object.DestroyImmediate(m_Canvas.gameObject);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e6323ebef616fee4486ee155cd56d191
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,88 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine.TestTools.Utils;
internal class GraphicRaycasterWorldSpaceCanvasTests
{
Camera m_Camera;
EventSystem m_EventSystem;
Canvas m_Canvas;
RectTransform m_CanvasRectTrans;
[SetUp]
public void TestSetup()
{
m_Camera = new GameObject("GraphicRaycaster Camera").AddComponent<Camera>();
m_Camera.transform.position = Vector3.zero;
m_Camera.transform.LookAt(Vector3.forward);
m_Camera.farClipPlane = 10;
m_EventSystem = new GameObject("Event System").AddComponent<EventSystem>();
m_Canvas = new GameObject("Canvas").AddComponent<Canvas>();
m_Canvas.renderMode = RenderMode.WorldSpace;
m_Canvas.worldCamera = m_Camera;
m_Canvas.gameObject.AddComponent<GraphicRaycaster>();
m_CanvasRectTrans = m_Canvas.GetComponent<RectTransform>();
m_CanvasRectTrans.sizeDelta = new Vector2(100, 100);
var textRectTrans = new GameObject("Text").AddComponent<Text>().rectTransform;
textRectTrans.SetParent(m_Canvas.transform);
textRectTrans.anchorMin = Vector2.zero;
textRectTrans.anchorMax = Vector2.one;
textRectTrans.offsetMin = Vector2.zero;
textRectTrans.offsetMax = Vector2.zero;
}
[UnityTest]
public IEnumerator GraphicRaycasterDoesNotHitGraphicBehindCameraFarClipPlane()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
Assert.IsEmpty(results, "Expected no results from a raycast against a graphic behind the camera's far clip plane.");
}
[UnityTest]
public IEnumerator GraphicRaycasterReturnsWorldPositionAndWorldNormal()
{
m_CanvasRectTrans.anchoredPosition3D = new Vector3(0, 0, 11);
m_Camera.farClipPlane = 12;
yield return null;
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
// on katana on 10.13 agents world position returned is 0, -0.00952, 11
// it does not reproduce for me localy, so we just tweak the comparison threshold
Assert.That(new Vector3(0, 0, 11), Is.EqualTo(results[0].worldPosition).Using(new Vector3EqualityComparer(0.01f)));
Assert.That(new Vector3(0, 0, -1), Is.EqualTo(results[0].worldNormal).Using(new Vector3EqualityComparer(0.001f)));
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_Camera.gameObject);
Object.DestroyImmediate(m_EventSystem.gameObject);
Object.DestroyImmediate(m_Canvas.gameObject);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d42c4854f9093e409cd90c00ef26de0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,316 @@
using System.Collections;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
[UnityPlatform()]
internal class InputModuleTests
{
EventSystem m_EventSystem;
FakeBaseInput m_FakeBaseInput;
StandaloneInputModule m_StandaloneInputModule;
Canvas m_Canvas;
Image m_Image;
Image m_NestedImage;
[SetUp]
public void TestSetup()
{
// Camera | Canvas (Image) | Event System
m_Canvas = new GameObject("Canvas").AddComponent<Canvas>();
m_Canvas.renderMode = RenderMode.ScreenSpaceOverlay;
m_Canvas.gameObject.AddComponent<GraphicRaycaster>();
m_Image = new GameObject("Image").AddComponent<Image>();
m_Image.gameObject.transform.SetParent(m_Canvas.transform);
RectTransform imageRectTransform = m_Image.GetComponent<RectTransform>();
imageRectTransform.sizeDelta = new Vector2(400f, 400f);
imageRectTransform.localPosition = Vector3.zero;
m_NestedImage = new GameObject("NestedImage").AddComponent<Image>();
m_NestedImage.gameObject.transform.SetParent(m_Image.transform);
RectTransform nestedImageRectTransform = m_NestedImage.GetComponent<RectTransform>();
nestedImageRectTransform.sizeDelta = new Vector2(200f, 200f);
nestedImageRectTransform.localPosition = Vector3.zero;
GameObject go = new GameObject("Event System");
m_EventSystem = go.AddComponent<EventSystem>();
m_EventSystem.pixelDragThreshold = 1;
m_StandaloneInputModule = go.AddComponent<StandaloneInputModule>();
m_FakeBaseInput = go.AddComponent<FakeBaseInput>();
// Override input with FakeBaseInput so we can send fake mouse/keyboards button presses and touches
m_StandaloneInputModule.inputOverride = m_FakeBaseInput;
Cursor.lockState = CursorLockMode.None;
}
[UnityTest]
public IEnumerator DragCallbacksDoGetCalled()
{
// While left mouse button is pressed and the mouse is moving, OnBeginDrag and OnDrag callbacks should be called
// Then when the left mouse button is released, OnEndDrag callback should be called
// Add script to EventSystem to update the mouse position
m_EventSystem.gameObject.AddComponent<MouseUpdate>();
// Add script to Image which implements OnBeginDrag, OnDrag & OnEndDrag callbacks
DragCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<DragCallbackCheck>();
// Setting required input.mousePresent to fake mouse presence
m_FakeBaseInput.MousePresent = true;
var canvasRT = m_Canvas.gameObject.transform as RectTransform;
m_FakeBaseInput.MousePosition = new Vector2(Screen.width / 2, Screen.height / 2);
yield return null;
// Left mouse button down simulation
m_FakeBaseInput.MouseButtonDown[0] = true;
yield return null;
// Left mouse button down flag needs to reset in the next frame
m_FakeBaseInput.MouseButtonDown[0] = false;
yield return null;
// Left mouse button up simulation
m_FakeBaseInput.MouseButtonUp[0] = true;
yield return null;
// Left mouse button up flag needs to reset in the next frame
m_FakeBaseInput.MouseButtonUp[0] = false;
yield return null;
Assert.IsTrue(callbackCheck.onBeginDragCalled, "OnBeginDrag not called");
Assert.IsTrue(callbackCheck.onDragCalled, "OnDragCalled not called");
Assert.IsTrue(callbackCheck.onEndDragCalled, "OnEndDragCalled not called");
Assert.IsTrue(callbackCheck.onDropCalled, "OnDrop not called");
}
[UnityTest]
public IEnumerator MouseOutsideMaskRectTransform_WhileInsidePaddedArea_PerformsClick()
{
var mask = new GameObject("Panel").AddComponent<RectMask2D>();
mask.gameObject.transform.SetParent(m_Canvas.transform);
RectTransform panelRectTransform = mask.GetComponent<RectTransform>();
panelRectTransform.sizeDelta = new Vector2(100, 100f);
panelRectTransform.localPosition = Vector3.zero;
m_Image.gameObject.transform.SetParent(mask.transform, true);
mask.padding = new Vector4(-30, -30, -30, -30);
PointerClickCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<PointerClickCallbackCheck>();
var canvasRT = m_Canvas.gameObject.transform as RectTransform;
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
// Click the center of the screen should hit the middle of the image.
m_FakeBaseInput.MouseButtonDown[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonDown[0] = false;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = false;
yield return null;
Assert.IsTrue(callbackCheck.pointerDown);
//Reset the callbackcheck and click outside the mask but still in the image.
callbackCheck.pointerDown = false;
m_FakeBaseInput.MousePosition = new Vector2(screenMiddle.x - 60, screenMiddle.y);
yield return null;
m_FakeBaseInput.MouseButtonDown[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonDown[0] = false;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = false;
yield return null;
Assert.IsTrue(callbackCheck.pointerDown);
//Reset the callbackcheck and click outside the mask and outside in the image.
callbackCheck.pointerDown = false;
m_FakeBaseInput.MousePosition = new Vector2(screenMiddle.x - 100, screenMiddle.y);
yield return null;
m_FakeBaseInput.MouseButtonDown[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonDown[0] = false;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = true;
yield return null;
m_FakeBaseInput.MouseButtonUp[0] = false;
yield return null;
Assert.IsFalse(callbackCheck.pointerDown);
}
[UnityTest]
public IEnumerator PointerEnterChildShouldNotFullyExit_NotSendPointerEventToParent()
{
m_StandaloneInputModule.sendPointerHoverToParent = false;
PointerExitCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<PointerExitCallbackCheck>();
m_NestedImage.gameObject.AddComponent<PointerExitCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
Assert.IsTrue(callbackCheck.pointerData.fullyExited == false);
}
[UnityTest]
public IEnumerator PointerEnterChildShouldNotExit_SendPointerEventToParent()
{
m_StandaloneInputModule.sendPointerHoverToParent = true;
PointerExitCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<PointerExitCallbackCheck>();
m_NestedImage.gameObject.AddComponent<PointerExitCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
Assert.IsTrue(callbackCheck.pointerData == null);
}
[UnityTest]
public IEnumerator PointerEnterChildShouldNotReenter()
{
PointerEnterCallbackCheck callbackCheck = m_NestedImage.gameObject.AddComponent<PointerEnterCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
Assert.IsTrue(callbackCheck.pointerData.reentered == false);
}
[UnityTest]
public IEnumerator PointerExitChildShouldReenter_NotSendPointerEventToParent()
{
m_StandaloneInputModule.sendPointerHoverToParent = false;
PointerEnterCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<PointerEnterCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
Assert.IsTrue(callbackCheck.pointerData.reentered == true);
}
[UnityTest]
public IEnumerator PointerExitChildShouldNotSendEnter_SendPointerEventToParent()
{
m_StandaloneInputModule.sendPointerHoverToParent = true;
m_NestedImage.gameObject.AddComponent<PointerEnterCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
PointerEnterCallbackCheck callbackCheck = m_Image.gameObject.AddComponent<PointerEnterCallbackCheck>();
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
Assert.IsTrue(callbackCheck.pointerData == null);
}
[UnityTest]
public IEnumerator PointerExitChildShouldFullyExit()
{
PointerExitCallbackCheck callbackCheck = m_NestedImage.gameObject.AddComponent<PointerExitCallbackCheck>();
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
m_FakeBaseInput.MousePresent = true;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
Assert.IsTrue(callbackCheck.pointerData.fullyExited == true);
}
[UnityTest]
public IEnumerator AllDragsAreReleasedOnLoseFocus()
{
// When the application loses focus, OnEndDrag and OnDrop should be called for all pointers
// involved in an active drag.
var screenMiddle = new Vector2(Screen.width / 2, Screen.height / 2);
// Add scripts to Image which implement OnBeginDrag, OnDrag & OnEndDrag callbacks
var callbackCheckLmb = m_Image.gameObject.AddComponent<DragCallbackCheck>();
callbackCheckLmb.pointerId = -1;
var callbackCheckRmb = m_Image.gameObject.AddComponent<DragCallbackCheck>();
callbackCheckRmb.pointerId = -2;
// Setting required to fake mouse presence
m_FakeBaseInput.MousePresent = true;
// Press both mouse buttons
m_FakeBaseInput.MouseButtonDown[0] = true;
m_FakeBaseInput.MouseButtonDown[1] = true;
m_FakeBaseInput.MousePosition = screenMiddle;
yield return null;
// Reset mouse down events and move pointer somewhere else -> initiates drag
m_FakeBaseInput.MouseButtonDown[0] = false;
m_FakeBaseInput.MouseButtonDown[1] = false;
m_FakeBaseInput.MousePosition = screenMiddle - new Vector2(150, 150);
yield return null;
// We should be mid-drag for both mouse buttons now
Assert.IsTrue(callbackCheckLmb.onBeginDragCalled, "OnBeginDrag not called for LMB");
Assert.IsTrue(callbackCheckRmb.onBeginDragCalled, "OnBeginDrag not called for RMB");
Assert.IsTrue(callbackCheckLmb.onDragCalled, "OnDrag not called for LMB");
Assert.IsTrue(callbackCheckRmb.onDragCalled, "OnDrag not called for RMB");
Assert.IsFalse(callbackCheckLmb.onEndDragCalled, "OnEndDrag called prematurely for LMB");
Assert.IsFalse(callbackCheckRmb.onEndDragCalled, "OnEndDrag called prematurely for RMB");
Assert.IsFalse(callbackCheckLmb.onDropCalled, "OnDrop called prematurely for LMB");
Assert.IsFalse(callbackCheckRmb.onDropCalled, "OnDrop called prematurely for RMB");
// Fake the application losing focus
typeof(EventSystem)
.GetMethod("OnApplicationFocus", BindingFlags.Instance | BindingFlags.NonPublic)
.Invoke(m_EventSystem, new object[] { false });
yield return null;
// Losing focus should have released the drags for both mouse buttons
Assert.IsTrue(callbackCheckLmb.onEndDragCalled, "OnEndDrag not called for LMB");
Assert.IsTrue(callbackCheckRmb.onEndDragCalled, "OnEndDrag not called for RMB");
Assert.IsTrue(callbackCheckLmb.onDropCalled, "OnDrop not called for LMB");
Assert.IsTrue(callbackCheckRmb.onDropCalled, "OnDrop not called for RMB");
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_EventSystem.gameObject);
GameObject.DestroyImmediate(m_Canvas.gameObject);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e4e290d31ab7fb54880746bb8f818e0d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7a892c920c8ad2848b469ec9579c5219
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
using System;
using UnityEngine;
using UnityEngine.EventSystems;
internal class DragCallbackCheck : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler, IPointerDownHandler
{
private bool loggedOnDrag = false;
[NonSerialized] public bool onBeginDragCalled = false;
[NonSerialized] public bool onDragCalled = false;
[NonSerialized] public bool onEndDragCalled = false;
[NonSerialized] public bool onDropCalled = false;
[NonSerialized] public int? pointerId = null;
public void OnBeginDrag(PointerEventData eventData)
{
if (pointerId.HasValue && eventData.pointerId != pointerId)
return;
onBeginDragCalled = true;
}
public void OnDrag(PointerEventData eventData)
{
if (pointerId.HasValue && eventData.pointerId != pointerId)
return;
if (loggedOnDrag)
return;
loggedOnDrag = true;
onDragCalled = true;
}
public void OnEndDrag(PointerEventData eventData)
{
if (pointerId.HasValue && eventData.pointerId != pointerId)
return;
onEndDragCalled = true;
}
public void OnDrop(PointerEventData eventData)
{
if (pointerId.HasValue && eventData.pointerId != pointerId)
return;
onDropCalled = true;
}
public void OnPointerDown(PointerEventData eventData)
{
// Empty to ensure we get the drop if we have a pointer handle as well.
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 76c82729ad712f14bae1a8a279c52ac3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,117 @@
using System;
using UnityEngine;
using UnityEngine.EventSystems;
internal class FakeBaseInput : BaseInput
{
[NonSerialized]
public String CompositionString = "";
private IMECompositionMode m_ImeCompositionMode = IMECompositionMode.Auto;
private Vector2 m_CompositionCursorPos = Vector2.zero;
[NonSerialized]
public bool MousePresent = false;
[NonSerialized]
public bool[] MouseButtonDown = new bool[3];
[NonSerialized]
public bool[] MouseButtonUp = new bool[3];
[NonSerialized]
public bool[] MouseButton = new bool[3];
[NonSerialized]
public Vector2 MousePosition = Vector2.zero;
[NonSerialized]
public Vector2 MouseScrollDelta = Vector2.zero;
[NonSerialized]
public bool TouchSupported = false;
[NonSerialized]
public int TouchCount = 0;
[NonSerialized]
public Touch TouchData;
[NonSerialized]
public float AxisRaw = 0f;
[NonSerialized]
public bool ButtonDown = false;
public override string compositionString
{
get { return CompositionString; }
}
public override IMECompositionMode imeCompositionMode
{
get { return m_ImeCompositionMode; }
set { m_ImeCompositionMode = value; }
}
public override Vector2 compositionCursorPos
{
get { return m_CompositionCursorPos; }
set { m_CompositionCursorPos = value; }
}
public override bool mousePresent
{
get { return MousePresent; }
}
public override bool GetMouseButtonDown(int button)
{
return MouseButtonDown[button];
}
public override bool GetMouseButtonUp(int button)
{
return MouseButtonUp[button];
}
public override bool GetMouseButton(int button)
{
return MouseButton[button];
}
public override Vector2 mousePosition
{
get { return MousePosition; }
}
public override Vector2 mouseScrollDelta
{
get { return MouseScrollDelta; }
}
public override bool touchSupported
{
get { return TouchSupported; }
}
public override int touchCount
{
get { return TouchCount; }
}
public override Touch GetTouch(int index)
{
return TouchData;
}
public override float GetAxisRaw(string axisName)
{
return AxisRaw;
}
public override bool GetButtonDown(string buttonName)
{
return ButtonDown;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 138dbec4f8742654fbceb0a19d68b9c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using UnityEngine;
internal class MouseUpdate : MonoBehaviour
{
FakeBaseInput m_FakeBaseInput;
void Awake()
{
m_FakeBaseInput = GetComponent<FakeBaseInput>();
}
void Update()
{
Debug.Assert(m_FakeBaseInput, "FakeBaseInput component has not been added to the EventSystem");
// Update mouse position
m_FakeBaseInput.MousePosition.x += 10f;
m_FakeBaseInput.MousePosition.y += 10f;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 19c6f364c1e81cb4f829a057824639ad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
internal class PointerClickCallbackCheck : MonoBehaviour, IPointerDownHandler
{
public bool pointerDown = false;
public void OnPointerDown(PointerEventData eventData)
{
pointerDown = true;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0573713975c6b8246b7544ed524ef1dc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
internal class PointerEnterCallbackCheck : MonoBehaviour, IPointerEnterHandler
{
public PointerEventData pointerData { get; private set; }
public void OnPointerEnter(PointerEventData eventData)
{
pointerData = eventData;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eb4fb871430ff484e9ee3850946c504d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
internal class PointerExitCallbackCheck : MonoBehaviour, IPointerExitHandler
{
public PointerEventData pointerData { get; private set; }
public void OnPointerExit(PointerEventData eventData)
{
pointerData = eventData;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: af94bd3a805f27e42ab86647265be74e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Rendering;
internal class Physics2DRaycasterTests
{
GameObject m_CamGO;
SpriteRenderer m_RedSprite;
SpriteRenderer m_BlueSprite;
SpriteRenderer m_GreenSprite;
EventSystem m_EventSystem;
[SetUp]
public void TestSetup()
{
m_CamGO = new GameObject("Physics2DRaycaster Camera");
m_CamGO.transform.position = new Vector3(0, 0, -10);
m_CamGO.transform.LookAt(Vector3.zero);
var cam = m_CamGO.AddComponent<Camera>();
cam.orthographic = true;
m_CamGO.AddComponent<Physics2DRaycaster>();
m_EventSystem = m_CamGO.AddComponent<EventSystem>();
var texture = new Texture2D(64, 64);
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
m_RedSprite = CreateTestSprite("Red", Color.red, sprite);
m_BlueSprite = CreateTestSprite("Blue", Color.blue, sprite);
m_GreenSprite = CreateTestSprite("Green", Color.green, sprite);
}
static SpriteRenderer CreateTestSprite(string name, Color color, Sprite sprite)
{
var go = new GameObject(name);
var sr = go.AddComponent<SpriteRenderer>();
sr.sprite = sprite;
sr.color = color;
go.AddComponent<BoxCollider2D>();
return sr;
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_CamGO);
Object.DestroyImmediate(m_RedSprite.gameObject);
Object.DestroyImmediate(m_BlueSprite.gameObject);
Object.DestroyImmediate(m_GreenSprite.gameObject);
}
static void AssertRaycastResultsOrder(List<RaycastResult> results, params SpriteRenderer[] expectedOrder)
{
Assert.AreEqual(expectedOrder.Length, results.Count);
for (int i = 0; i < expectedOrder.Length; ++i)
{
Assert.AreSame(expectedOrder[i].gameObject, results[i].gameObject, "Expected {0} at index {1} but got {2}", expectedOrder[i], i, results[i].gameObject);
}
}
List<RaycastResult> PerformRaycast()
{
var results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(m_EventSystem)
{
position = new Vector2(Screen.width / 2f, Screen.height / 2f)
};
m_EventSystem.RaycastAll(pointerEvent, results);
return results;
}
[Test]
public void RaycastAllResultsAreSortedByRendererSortingOrder()
{
m_RedSprite.sortingOrder = -10;
m_BlueSprite.sortingOrder = 0;
m_GreenSprite.sortingOrder = 5;
var results = PerformRaycast();
AssertRaycastResultsOrder(results, m_GreenSprite, m_BlueSprite, m_RedSprite);
}
[Test]
public void RaycastAllResultsAreSortedBySortGroupOrder()
{
var blueSg = m_BlueSprite.gameObject.AddComponent<SortingGroup>();
blueSg.sortingLayerID = 0;
blueSg.sortingOrder = -10;
var redSg = m_RedSprite.gameObject.AddComponent<SortingGroup>();
redSg.sortingLayerID = 0;
redSg.sortingOrder = 10;
SortingGroup.UpdateAllSortingGroups();
var results = PerformRaycast();
AssertRaycastResultsOrder(results, m_RedSprite, m_GreenSprite, m_BlueSprite);
}
[Test]
public void RaycastAllResultsAreSortedBySortGroupOrderAndSortingOrder()
{
m_RedSprite.sortingOrder = -10;
m_BlueSprite.sortingOrder = 0;
m_GreenSprite.sortingOrder = 5;
var sg = m_BlueSprite.gameObject.AddComponent<SortingGroup>();
sg.sortingLayerID = 0;
sg.sortingOrder = 100;
SortingGroup.UpdateAllSortingGroups();
var results = PerformRaycast();
AssertRaycastResultsOrder(results, m_BlueSprite, m_GreenSprite, m_RedSprite);
}
[Test]
public void RaycastAllResultsAreSortedBySortGroupDistanceAlongRay()
{
// Ensure we use the distance along the raycast to sort the results
var sortingGroupRed = new GameObject("Sorting Group Red", typeof(SortingGroup));
var sortingGroupBlue = new GameObject("Sorting Group Blue", typeof(SortingGroup));
var sortingGroupGreen = new GameObject("Sorting Group Green", typeof(SortingGroup));
sortingGroupRed.transform.position = new Vector3(0, 0, -1);
sortingGroupBlue.transform.position = new Vector3(1000, 1000, 0);
sortingGroupGreen.transform.position = new Vector3(0, 0, 1);
m_RedSprite.transform.SetParent(sortingGroupRed.transform, true);
m_BlueSprite.transform.SetParent(sortingGroupBlue.transform, true);
m_GreenSprite.transform.SetParent(sortingGroupGreen.transform, true);
SortingGroup.UpdateAllSortingGroups();
var results = PerformRaycast();
AssertRaycastResultsOrder(results, m_RedSprite, m_BlueSprite, m_GreenSprite);
// Unparent so they can be destroyed by the TearDown
m_RedSprite.transform.parent = null;
m_BlueSprite.transform.parent = null;
m_GreenSprite.transform.parent = null;
// Cleanup
Object.DestroyImmediate(sortingGroupRed);
Object.DestroyImmediate(sortingGroupBlue);
Object.DestroyImmediate(sortingGroupGreen);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6fb761a492f57d84586a8264df7b3cc0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,46 @@
using UnityEngine;
using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine.EventSystems;
internal class PhysicsRaycasterTests
{
GameObject m_CamGO;
GameObject m_Collider;
[SetUp]
public void TestSetup()
{
m_CamGO = new GameObject("PhysicsRaycaster Camera");
m_Collider = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
[Test]
public void PhysicsRaycasterDoesNotCastOutsideCameraViewRect()
{
m_CamGO.transform.position = new Vector3(0, 0, -10);
m_CamGO.transform.LookAt(Vector3.zero);
var cam = m_CamGO.AddComponent<Camera>();
cam.rect = new Rect(0.5f, 0, 0.5f, 1);
m_CamGO.AddComponent<PhysicsRaycaster>();
var eventSystem = m_CamGO.AddComponent<EventSystem>();
// Create an object that will be hit if a raycast does occur.
m_Collider.transform.localScale = new Vector3(100, 100, 1);
List<RaycastResult> results = new List<RaycastResult>();
var pointerEvent = new PointerEventData(eventSystem)
{
position = new Vector2(0, 0) // Raycast from the left side of the screen which is outside of the camera's view rect.
};
eventSystem.RaycastAll(pointerEvent, results);
Assert.IsEmpty(results, "Expected no results from a raycast that is outside of the camera's viewport.");
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CamGO);
GameObject.DestroyImmediate(m_Collider);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 833143c443f979e44ae0b8ed899e3b59
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,126 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.EventSystems;
#endif
internal class RaycastSortingTests : IPrebuildSetup
{
// Test to check that a a raycast over two canvases will not use hierarchal depth to compare two results
// from different canvases (case 912396 - Raycast hits ignores 2nd Canvas which is drawn in front)
GameObject m_PrefabRoot;
const string kPrefabPath = "Assets/Resources/RaycastSortingPrefab.prefab";
void IPrebuildSetup.Setup()
{
#if UNITY_EDITOR
var rootGO = new GameObject("RootGO");
var cameraGO = new GameObject("Camera", typeof(Camera));
var camera = cameraGO.GetComponent<Camera>();
cameraGO.transform.SetParent(rootGO.transform);
var eventSystemGO = new GameObject("EventSystem", typeof(EventSystem));
InputModuleComponentFactory.AddInputModule(eventSystemGO);
eventSystemGO.transform.SetParent(rootGO.transform);
var backCanvasGO = new GameObject("BackCanvas", typeof(Canvas), typeof(GraphicRaycaster));
backCanvasGO.transform.SetParent(rootGO.transform);
var backCanvas = backCanvasGO.GetComponent<Canvas>();
backCanvas.renderMode = RenderMode.ScreenSpaceCamera;
backCanvas.planeDistance = 100;
backCanvas.worldCamera = camera;
var backCanvasBackground = new GameObject("BackCanvasBackground", typeof(RectTransform), typeof(Image));
var backCanvasBackgroundTransform = backCanvasBackground.GetComponent<RectTransform>();
backCanvasBackgroundTransform.SetParent(backCanvasGO.transform);
backCanvasBackgroundTransform.anchorMin = Vector2.zero;
backCanvasBackgroundTransform.anchorMax = Vector2.one;
backCanvasBackgroundTransform.sizeDelta = Vector2.zero;
backCanvasBackgroundTransform.anchoredPosition3D = Vector3.zero;
backCanvasBackgroundTransform.localScale = Vector3.one;
var backCanvasDeeper = new GameObject("BackCanvasDeeperHierarchy", typeof(RectTransform), typeof(Image));
var backCanvasDeeperTransform = backCanvasDeeper.GetComponent<RectTransform>();
backCanvasDeeperTransform.SetParent(backCanvasBackgroundTransform);
backCanvasDeeperTransform.anchorMin = new Vector2(0.5f, 0);
backCanvasDeeperTransform.anchorMax = Vector2.one;
backCanvasDeeperTransform.sizeDelta = Vector2.zero;
backCanvasDeeperTransform.anchoredPosition3D = Vector3.zero;
backCanvasDeeperTransform.localScale = Vector3.one;
backCanvasDeeper.GetComponent<Image>().color = new Color(0.6985294f, 0.7754564f, 1f);
var frontCanvasGO = new GameObject("FrontCanvas", typeof(Canvas), typeof(GraphicRaycaster));
frontCanvasGO.transform.SetParent(rootGO.transform);
var frontCanvas = frontCanvasGO.GetComponent<Canvas>();
frontCanvas.renderMode = RenderMode.ScreenSpaceCamera;
frontCanvas.planeDistance = 50;
frontCanvas.worldCamera = camera;
var frontCanvasTopLevel = new GameObject("FrontCanvasTopLevel", typeof(RectTransform), typeof(Text));
var frontCanvasTopLevelTransform = frontCanvasTopLevel.GetComponent<RectTransform>();
frontCanvasTopLevelTransform.SetParent(frontCanvasGO.transform);
frontCanvasTopLevelTransform.anchorMin = Vector2.zero;
frontCanvasTopLevelTransform.anchorMax = new Vector2(1, 0.5f);
frontCanvasTopLevelTransform.sizeDelta = Vector2.zero;
frontCanvasTopLevelTransform.anchoredPosition3D = Vector3.zero;
frontCanvasTopLevelTransform.localScale = Vector3.one;
var text = frontCanvasTopLevel.GetComponent<Text>();
text.text = "FrontCanvasTopLevel";
text.color = Color.black;
text.fontSize = 97;
if (!Directory.Exists("Assets/Resources/"))
Directory.CreateDirectory("Assets/Resources/");
UnityEditor.PrefabUtility.SaveAsPrefabAsset(rootGO, kPrefabPath);
GameObject.DestroyImmediate(rootGO);
#endif
}
[SetUp]
public void TestSetup()
{
m_PrefabRoot = Object.Instantiate(Resources.Load("RaycastSortingPrefab")) as GameObject;
}
[UnityTest]
public IEnumerator RaycastResult_Sorting()
{
Camera cam = m_PrefabRoot.GetComponentInChildren<Camera>();
EventSystem eventSystem = m_PrefabRoot.GetComponentInChildren<EventSystem>();
GameObject shouldHit = m_PrefabRoot.GetComponentInChildren<Text>().gameObject;
PointerEventData eventData = new PointerEventData(eventSystem);
//bottom left quadrant
eventData.position = cam.ViewportToScreenPoint(new Vector3(0.75f, 0.25f));
List<RaycastResult> results = new List<RaycastResult>();
eventSystem.RaycastAll(eventData, results);
Assert.IsTrue(results[0].gameObject.name == shouldHit.name);
yield return null;
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_PrefabRoot);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(kPrefabPath);
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0ca2545d76d1fb34fa45a9f1e432d259
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,468 @@
using System.Reflection;
using System.Collections;
using NUnit.Framework;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
namespace UnityEngine.UI.Tests
{
[TestFixture]
class SelectableTests
{
private class SelectableTest : Selectable
{
public bool isStateNormal { get { return currentSelectionState == SelectionState.Normal; } }
public bool isStateHighlighted { get { return currentSelectionState == SelectionState.Highlighted; } }
public bool isStateSelected { get { return currentSelectionState == SelectionState.Selected; } }
public bool isStatePressed { get { return currentSelectionState == SelectionState.Pressed; } }
public bool isStateDisabled { get { return currentSelectionState == SelectionState.Disabled; } }
public Selectable GetSelectableAtIndex(int index)
{
return s_Selectables[index];
}
public int GetSelectableCurrentIndex()
{
return m_CurrentIndex;
}
}
private SelectableTest selectable;
private GameObject m_CanvasRoot;
private GameObject m_EventSystemGO;
private CanvasGroup CreateAndParentGroupTo(string name, GameObject child)
{
GameObject canvasRoot = new GameObject("Canvas", typeof(RectTransform), typeof(Canvas));
GameObject groupGO = new GameObject(name, typeof(RectTransform), typeof(CanvasGroup));
groupGO.transform.SetParent(canvasRoot.transform);
child.transform.SetParent(groupGO.transform);
return groupGO.GetComponent<CanvasGroup>();
}
[SetUp]
public void TestSetup()
{
m_EventSystemGO = new GameObject("EventSystem", typeof(EventSystem));
EventSystem.current = m_EventSystemGO.GetComponent<EventSystem>();
m_CanvasRoot = new GameObject("Canvas", typeof(RectTransform), typeof(Canvas));
GameObject SelectableGO = new GameObject("Selectable", typeof(RectTransform), typeof(CanvasRenderer));
SelectableGO.transform.SetParent(m_CanvasRoot.transform);
selectable = SelectableGO.AddComponent<SelectableTest>();
selectable.targetGraphic = selectable.gameObject.AddComponent<ConcreteGraphic>();
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasRoot);
GameObject.DestroyImmediate(m_EventSystemGO);
}
[Test] // regression test 1160054
public void SelectableArrayRemovesReferenceUponDisable()
{
int originalSelectableCount = Selectable.allSelectableCount;
selectable.enabled = false;
Assert.AreEqual(originalSelectableCount - 1, Selectable.allSelectableCount, "We have more then originalSelectableCount - 1 selectable objects.");
//ensure the item as the last index is nulled out as it replaced the item that was disabled.
Assert.IsNull(selectable.GetSelectableAtIndex(Selectable.allSelectableCount));
selectable.enabled = true;
}
#region Selected object
[Test]
public void SettingCurrentSelectedSelectableNonInteractableShouldNullifyCurrentSelected()
{
EventSystem.current.SetSelectedGameObject(selectable.gameObject);
selectable.interactable = false;
// it should be unselected now that it is not interactable anymore
Assert.IsNull(EventSystem.current.currentSelectedGameObject);
}
[Test]
public void PointerEnterDownShouldMakeItSelectedGameObject()
{
Assert.IsNull(EventSystem.current.currentSelectedGameObject);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current));
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
Assert.AreEqual(selectable.gameObject, EventSystem.current.currentSelectedGameObject);
}
[Test]
public void OnSelectShouldSetSelectedState()
{
Assert.True(selectable.isStateNormal);
selectable.OnSelect(new BaseEventData(EventSystem.current));
Assert.True(selectable.isStateSelected);
}
[Test]
public void OnDeselectShouldUnsetSelectedState()
{
Assert.True(selectable.isStateNormal);
selectable.OnSelect(new BaseEventData(EventSystem.current));
Assert.True(selectable.isStateSelected);
selectable.OnDeselect(new BaseEventData(EventSystem.current));
Assert.True(selectable.isStateNormal);
}
#endregion
#region Interactable
[Test]
public void SettingCanvasGroupNotInteractableShouldMakeSelectableNotInteractable()
{
// Canvas Group on same object
var group = selectable.gameObject.AddComponent<CanvasGroup>();
Assert.IsTrue(selectable.IsInteractable());
group.interactable = false;
// actual call happens on the native side, cause by interactable = false
selectable.InvokeOnCanvasGroupChanged();
Assert.IsFalse(selectable.IsInteractable());
}
[Test]
public void DisablingCanvasGroupShouldMakeSelectableAsInteractable()
{
var group = selectable.gameObject.AddComponent<CanvasGroup>();
Assert.IsTrue(selectable.IsInteractable());
group.enabled = false;
group.interactable = false;
selectable.InvokeOnCanvasGroupChanged();
Assert.IsTrue(selectable.IsInteractable());
}
[Test]
public void SettingParentCanvasGroupNotInteractableShouldMakeSelectableNotInteractable()
{
var canvasGroup = CreateAndParentGroupTo("CanvasGroup", selectable.gameObject);
Assert.IsTrue(selectable.IsInteractable());
canvasGroup.interactable = false;
// actual call happens on the native side, cause by interactable = false
selectable.InvokeOnCanvasGroupChanged();
Assert.IsFalse(selectable.IsInteractable());
}
[Test]
public void SettingParentParentCanvasGroupNotInteractableShouldMakeSelectableNotInteractable()
{
var canvasGroup1 = CreateAndParentGroupTo("CanvasGroup1", selectable.gameObject);
var canvasGroup2 = CreateAndParentGroupTo("CanvasGroup2", canvasGroup1.gameObject);
Assert.IsTrue(selectable.IsInteractable());
canvasGroup2.interactable = false;
// actual call happens on the native side, cause by interactable = false
selectable.InvokeOnCanvasGroupChanged();
Assert.IsFalse(selectable.IsInteractable());
}
[Test]
public void SettingParentParentCanvasGroupInteractableShouldMakeSelectableInteractable()
{
var canvasGroup1 = CreateAndParentGroupTo("CanvasGroup1", selectable.gameObject);
CreateAndParentGroupTo("CanvasGroup2", canvasGroup1.gameObject);
Assert.IsTrue(selectable.IsInteractable());
// actual call happens on the native side, cause by interactable
selectable.InvokeOnCanvasGroupChanged();
Assert.IsTrue(selectable.IsInteractable());
}
[Test]
public void SettingParentParentCanvasGroupNotInteractableShouldNotMakeSelectableNotInteractableIfIgnoreParentGroups()
{
var canvasGroup1 = CreateAndParentGroupTo("CanvasGroup1", selectable.gameObject);
canvasGroup1.ignoreParentGroups = true;
var canvasGroup2 = CreateAndParentGroupTo("CanvasGroup2", canvasGroup1.gameObject);
Assert.IsTrue(selectable.IsInteractable());
canvasGroup2.interactable = false;
// actual call happens on the native side, cause by interactable = false
selectable.InvokeOnCanvasGroupChanged();
Assert.IsTrue(selectable.IsInteractable());
}
[Test]// regression test 861736
public void PointerEnterThenSetNotInteractableThenExitThenSetInteractableShouldSetStateToDefault()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
Assert.True(selectable.isStateHighlighted);
selectable.interactable = false;
selectable.InvokeOnPointerExit(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.interactable = true;
Assert.False(selectable.isStateHighlighted);
Assert.True(selectable.isStateNormal);
}
[Test]// regression test 861736
public void PointerEnterThenSetNotInteractableThenSetInteractableShouldStayHighlighted()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
Assert.True(selectable.isStateHighlighted);
selectable.interactable = false;
selectable.interactable = true;
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void InstantiatingSelectableUnderNotInteractableCanvasGroupShouldAlsoNotBeInteractable()
{
var canvasGroup = CreateAndParentGroupTo("ParentGroup", selectable.gameObject);
canvasGroup.interactable = false;
Assert.False(canvasGroup.interactable);
var newSelectable = Object.Instantiate(selectable.gameObject, canvasGroup.transform).GetComponent<SelectableTest>();
Assert.False(newSelectable.IsInteractable());
}
#endregion
#region Tweening
[UnityTest]
public IEnumerator SettingNotInteractableShouldTweenToDisabledColor()
{
var canvasRenderer = selectable.gameObject.GetComponent<CanvasRenderer>();
selectable.InvokeOnEnable();
canvasRenderer.SetColor(selectable.colors.normalColor);
selectable.interactable = false;
yield return new WaitForSeconds(1);
Assert.AreEqual(selectable.colors.disabledColor, canvasRenderer.GetColor());
selectable.interactable = true;
yield return new WaitForSeconds(1);
Assert.AreEqual(selectable.colors.normalColor, canvasRenderer.GetColor());
}
[UnityTest]
public IEnumerator SettingInteractableToFalseTrueFalseShouldTweenToDisabledColor()
{
var canvasRenderer = selectable.gameObject.GetComponent<CanvasRenderer>();
selectable.InvokeOnEnable();
canvasRenderer.SetColor(selectable.colors.normalColor);
selectable.interactable = false;
selectable.interactable = true;
selectable.interactable = false;
yield return new WaitForSeconds(1);
Assert.AreEqual(selectable.colors.disabledColor, canvasRenderer.GetColor());
}
#if PACKAGE_ANIMATION
[Test]
public void TriggerAnimationWithNoAnimator()
{
Assert.Null(selectable.animator);
Assert.DoesNotThrow(() => selectable.InvokeTriggerAnimation("asdasd"));
}
[Test]
public void TriggerAnimationWithDisabledAnimator()
{
var an = selectable.gameObject.AddComponent<Animator>();
an.enabled = false;
Assert.NotNull(selectable.animator);
Assert.DoesNotThrow(() => selectable.InvokeTriggerAnimation("asdasd"));
}
[Test]
public void TriggerAnimationAnimatorWithNoRuntimeController()
{
var an = selectable.gameObject.AddComponent<Animator>();
an.runtimeAnimatorController = null;
Assert.NotNull(selectable.animator);
Assert.DoesNotThrow(() => selectable.InvokeTriggerAnimation("asdasd"));
}
#endif
#endregion
#region Selection state and pointer
[Test]
public void SelectShouldSetSelectedObject()
{
Assert.Null(EventSystem.current.currentSelectedGameObject);
selectable.Select();
Assert.AreEqual(selectable.gameObject, EventSystem.current.currentSelectedGameObject);
}
[Test]
public void SelectWhenAlreadySelectingShouldNotSetSelectedObject()
{
Assert.Null(EventSystem.current.currentSelectedGameObject);
var fieldInfo = typeof(EventSystem).GetField("m_SelectionGuard", BindingFlags.NonPublic | BindingFlags.Instance);
fieldInfo
.SetValue(EventSystem.current, true);
selectable.Select();
Assert.Null(EventSystem.current.currentSelectedGameObject);
}
[Test]
public void PointerEnterShouldHighlight()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void PointerEnterOnSelectedObjectShouldStaySelected()
{
selectable.InvokeOnSelect(null);
Assert.True(selectable.isStateSelected);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
Assert.True(selectable.isStateSelected);
}
[Test]
public void PointerEnterAndRightClickShouldHighlightNotPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current)
{
button = PointerEventData.InputButton.Right
});
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void PointerEnterAndRightClickShouldPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
Assert.True(selectable.isStatePressed);
}
[Test]
public void PointerEnterLeftClickExitShouldPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
selectable.InvokeOnPointerExit(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
Assert.True(selectable.isStatePressed);
}
[Test]
public void PointerEnterLeftClickExitReleaseShouldSelect()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
selectable.InvokeOnPointerExit(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerUp(new PointerEventData(EventSystem.current));
Assert.True(selectable.isStateSelected);
}
[Test]
public void PointerDownShouldSetSelectedObject()
{
Assert.Null(EventSystem.current.currentSelectedGameObject);
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
Assert.AreEqual(selectable.gameObject, EventSystem.current.currentSelectedGameObject);
}
[Test]
public void PointerLeftDownRightDownRightUpShouldNotChangeState()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(new PointerEventData(EventSystem.current)
{
pointerEnter = selectable.gameObject
});
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current) { button = PointerEventData.InputButton.Left });
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current) { button = PointerEventData.InputButton.Right });
selectable.InvokeOnPointerUp(new PointerEventData(EventSystem.current) { button = PointerEventData.InputButton.Right });
Assert.True(selectable.isStatePressed);
}
#endregion
#region No event system
[Test] // regression test 787563
public void SettingInteractableWithNoEventSystemShouldNotCrash()
{
EventSystem.current.enabled = false;
selectable.interactable = false;
}
[Test] // regression test 787563
public void OnPointerDownWithNoEventSystemShouldNotCrash()
{
EventSystem.current.enabled = false;
selectable.OnPointerDown(new PointerEventData(EventSystem.current) {button = PointerEventData.InputButton.Left});
}
[Test] // regression test 787563
public void SelectWithNoEventSystemShouldNotCrash()
{
EventSystem.current.enabled = false;
selectable.Select();
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 39dcddcb5895328489c92214aa73e3bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: