Initial Commit

This commit is contained in:
Sebastian Cabrera 2021-08-02 05:44:37 -04:00
parent 53eb92e9af
commit 270ab7d11f
15341 changed files with 700234 additions and 0 deletions

View file

@ -0,0 +1,132 @@
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;
public 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 ");
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_Camera.gameObject);
Object.DestroyImmediate(m_EventSystem.gameObject);
Object.DestroyImmediate(m_Canvas.gameObject);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e6323ebef616fee4486ee155cd56d191
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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;
public 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);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d42c4854f9093e409cd90c00ef26de0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,157 @@
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
public class InputModuleTests
{
EventSystem m_EventSystem;
FakeBaseInput m_FakeBaseInput;
StandaloneInputModule m_StandaloneInputModule;
Canvas m_Canvas;
Image m_Image;
[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;
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);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_EventSystem.gameObject);
GameObject.DestroyImmediate(m_Canvas.gameObject);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e4e290d31ab7fb54880746bb8f818e0d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7a892c920c8ad2848b469ec9579c5219
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,40 @@
using UnityEngine;
using UnityEngine.EventSystems;
public class DragCallbackCheck : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler, IPointerDownHandler
{
private bool loggedOnDrag = false;
public bool onBeginDragCalled = false;
public bool onDragCalled = false;
public bool onEndDragCalled = false;
public bool onDropCalled = false;
public void OnBeginDrag(PointerEventData eventData)
{
onBeginDragCalled = true;
}
public void OnDrag(PointerEventData eventData)
{
if (loggedOnDrag)
return;
loggedOnDrag = true;
onDragCalled = true;
}
public void OnEndDrag(PointerEventData eventData)
{
onEndDragCalled = true;
}
public void OnDrop(PointerEventData eventData)
{
onDropCalled = true;
}
public void OnPointerDown(PointerEventData eventData)
{
// Empty to ensure we get the drop if we have a pointer handle as well.
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 76c82729ad712f14bae1a8a279c52ac3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,117 @@
using System;
using UnityEngine;
using UnityEngine.EventSystems;
public 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;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 138dbec4f8742654fbceb0a19d68b9c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,20 @@
using UnityEngine;
public 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;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 19c6f364c1e81cb4f829a057824639ad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PointerClickCallbackCheck : MonoBehaviour, IPointerDownHandler
{
public bool pointerDown = false;
public void OnPointerDown(PointerEventData eventData)
{
pointerDown = true;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0573713975c6b8246b7544ed524ef1dc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,46 @@
using UnityEngine;
using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public 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);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 833143c443f979e44ae0b8ed899e3b59
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,121 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
public 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";
public void 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), typeof(StandaloneInputModule));
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
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0ca2545d76d1fb34fa45a9f1e432d259
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,439 @@
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 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(null);
Assert.True(selectable.isStateHighlighted);
selectable.interactable = false;
selectable.InvokeOnPointerExit(null);
selectable.interactable = true;
Assert.False(selectable.isStateHighlighted);
Assert.True(selectable.isStateNormal);
}
[Test]// regression test 861736
public void PointerEnterThenSetNotInteractableThenSetInteractableShouldStayHighlighted()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(null);
Assert.True(selectable.isStateHighlighted);
selectable.interactable = false;
selectable.interactable = true;
Assert.True(selectable.isStateHighlighted);
}
#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][Ignore("Fails")] // regression test 742140
public IEnumerator SettingNotInteractableThenInteractableShouldNotTweenToDisabledColor()
{
var canvasRenderer = selectable.gameObject.GetComponent<CanvasRenderer>();
selectable.enabled = false;
selectable.enabled = true;
canvasRenderer.SetColor(selectable.colors.normalColor);
selectable.interactable = false;
selectable.interactable = true;
Color c = canvasRenderer.GetColor();
for (int i = 0; i < 30; i++)
{
yield return null;
Color c2 = canvasRenderer.GetColor();
Assert.AreNotEqual(c2, c);
}
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(null);
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void PointerEnterOnSelectedObjectShouldHighlight()
{
selectable.InvokeOnSelect(null);
Assert.True(selectable.isStateSelected);
selectable.InvokeOnPointerEnter(null);
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void PointerEnterAndRightClickShouldHighlightNotPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(null);
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current)
{
button = PointerEventData.InputButton.Right
});
Assert.True(selectable.isStateHighlighted);
}
[Test]
public void PointerEnterAndRightClickShouldPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(null);
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
Assert.True(selectable.isStatePressed);
}
[Test]
public void PointerEnterLeftClickExitShouldPress()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(null);
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
selectable.InvokeOnPointerExit(null);
Assert.True(selectable.isStatePressed);
}
[Test]
public void PointerEnterLeftClickExitReleaseShouldSelect()
{
Assert.True(selectable.isStateNormal);
selectable.InvokeOnPointerEnter(null);
selectable.InvokeOnPointerDown(new PointerEventData(EventSystem.current));
selectable.InvokeOnPointerExit(null);
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(null);
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);
}
[Test, Ignore("No disabled state assigned ? Investigate")]
public void SettingNotInteractableShouldDisable()
{
Assert.True(selectable.isStateNormal);
selectable.interactable = false;
selectable.InvokeOnCanvasGroupChanged();
Assert.True(selectable.isStateDisabled);
}
#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
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 39dcddcb5895328489c92214aa73e3bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: