This commit is contained in:
2025-01-17 13:10:42 +01:00
commit 4536213c91
15115 changed files with 1442174 additions and 0 deletions

View File

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

View File

@@ -0,0 +1,48 @@
using UnityEngine;
using NUnit.Framework;
using System.IO;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace TMPro
{
public class TMP_CanvasTests
{
[OneTimeSetUp]
public void Setup()
{
if (!Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")))
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
Assert.Ignore();
return;
}
}
[Test]
public void EnablingAndDisablingCanvasDoesNotRegenerateText() // (UUM-45320)
{
var go = new GameObject();
var canvas = go.AddComponent<Canvas>();
var goChild = new GameObject();
var text = goChild.AddComponent<TextMeshProUGUI>();
goChild.transform.SetParent(go.transform);
// Force text to be generated
text.text = "Hello World";
text.ForceMeshUpdate();
Assert.IsFalse(text.havePropertiesChanged, "Text should not have changed yet");
canvas.enabled = false;
canvas.enabled = true;
Assert.IsFalse(text.havePropertiesChanged, "Text should not have changed after enabling / disabling canvas");
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5348cbfcd4f74699b33fe6b43747a016
timeCreated: 1703006962

View File

@@ -0,0 +1,278 @@
using UnityEngine;
using NUnit.Framework;
using System.IO;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace TMPro
{
[Category("Text Parsing & Layout")]
class TMP_RuntimeTests
{
private TextMeshPro m_TextComponent;
// Characters: 22 Spaces: 4 Words: 5 Lines:
private const string m_TextBlock_00 = "A simple line of text.";
// Characters: 104 Spaces: 14 Words: 15 Lines:
private const string m_TextBlock_01 = "Unity 2017 introduces new features that help teams of artists and developers build experiences together.";
// Characters: 1500 Spaces: 228 Words: 241
private const string m_TextBlock_02 = "The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words." +
"Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators.To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words.If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages." +
"The new common language will be more simple and regular than the existing European languages.It will be as simple as Occidental; in fact, it will be Occidental.To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is. The European languages are members of the same family." +
"Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary.The languages only differ in their grammar, their pronunciation and their most common words.Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators.To achieve this, it would be necessary to" +
"have uniform grammar, pronunciation and more common words.If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages.The new common language will be";
// Characters: 2500 Spaces: 343 Words: 370
private const string m_TextBlock_03 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. " +
"Nullam dictum felis eu pede mollis pretium.Integer tincidunt.Cras dapibus.Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.Phasellus viverra nulla ut metus varius laoreet.Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.Curabitur ullamcorper ultricies nisi. " +
"Nam eget dui.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem.Maecenas nec odio et ante tincidunt tempus.Donec vitae sapien ut libero venenatis faucibus.Nullam quis ante.Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. " +
"Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.Nullam accumsan lorem in dui.Cras ultricies mi eu turpis hendrerit fringilla.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. " +
"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris.Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris.Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc.Nunc nonummy metus.Vestibulum volutpat pretium libero. Cras id dui.Aenean ut eros et nisl sagittis vestibulum.Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede.Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. " +
"Etiam imperdiet imperdiet orci. Nunc nec neque.Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi.Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo.Maecenas malesuada. Praesent nan. The end of this of this long block of text.";
// Characters: 3423 Spaces: 453 Words: 500
private const string m_TextBlock_04 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Aenean commodo ligula eget dolor.Aenean massa.Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.Nulla consequat massa quis enim.Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.Nullam dictum felis eu pede mollis pretium.Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus." +
"Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.Phasellus viverra nulla ut metus varius laoreet.Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.Curabitur ullamcorper ultricies nisi. Nam eget dui.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem.Maecenas nec odio et ante tincidunt tempus.Donec vitae sapien ut libero venenatis faucibus.Nullam quis ante." +
"Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.Nullam accumsan lorem in dui.Cras ultricies mi eu turpis hendrerit fringilla.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia.Nam pretium turpis et arcu." +
"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris.Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris.Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc.Nunc nonummy metus.Vestibulum volutpat pretium libero. Cras id dui.Aenean ut eros et nisl sagittis vestibulum.Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede.Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis.Etiam imperdiet imperdiet orci. Nunc nec neque." +
"Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi.Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo.Maecenas malesuada. Praesent congue erat at massa.Sed cursus turpis vitae tortor.Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci.Phasellus consectetuer vestibulum elit.Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc.Vestibulum fringilla pede sit amet augue." +
"In turpis. Pellentesque posuere. Praesent turpis. Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec, volutpat a, suscipit non, turpis.Nullam sagittis. Suspendisse pulvinar, augue ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus.Ut varius tincidunt libero.Phasellus dolor.Maecenas vestibulum mollis";
//
private const string m_TextBlock_05 = "This block of text contains <b>bold</b> and <i>italicized</i> characters.";
private const string m_TextBlock_06 = "<align=center><style=H1><#ffffff><u>Multiple<#80f0ff> Alignment</color> per text object</u></color></style></align><line-height=2em>\n" +
"</line-height> The <<#ffffa0>align</color>> tag in TextMesh<#40a0ff>Pro</color> provides the ability to control the alignment of lines and paragraphs which is essential when working with text.\n" +
"<align=left> You may want some block of text to be<#80f0ff>left aligned</color> <<#ffffa0>align=<#80f0ff>left</color></color>> which is sort of the standard.</align>\n" +
"<style=Quote><#ffffa0>\"Using <#80f0ff>Center Alignment</color> <<#ffffa0>align=<#80f0ff>center</color></color>> for a title or displaying a quote is another good example of text alignment.\"</color></style>\n" +
"<align=right><#80f0ff>Right Alignment</color> <<#ffffa0>align=<#80f0ff>right</color></color>> can be useful to create contrast between lines and paragraphs of text.\n" +
"<align=justified><#80f0ff>Justified Alignment</color> <<#ffffa0>align=<#80f0ff>justified</color></color>> results in text that is flush on both the left and right margins. Used well, justified type can look clean and classy.\n" +
"<style=Quote><align=left><#ffffa0>\"Text formatting and alignment has a huge impact on how people will read and perceive your text.\"</color>\n" +
"<size=65%><align=right> -Stephan Bouchard</style>";
private readonly string[] testStrings = new string[] { m_TextBlock_00, m_TextBlock_01, m_TextBlock_02, m_TextBlock_03, m_TextBlock_04, m_TextBlock_05, m_TextBlock_06 };
[OneTimeSetUp]
public void Setup()
{
if (Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")) || Directory.Exists(Path.GetFullPath("Packages/com.unity.textmeshpro.tests/TextMesh Pro")))
{
GameObject textObject = new GameObject("Text Object");
m_TextComponent = textObject.AddComponent<TextMeshPro>();
m_TextComponent.fontSize = 18;
}
else
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
Assert.Ignore();
return;
}
}
public static IEnumerable<object[]> TestCases_Parsing_TextInfo_WordWrapDisabled()
{
yield return new object[] { 0, 22, 4, 5, 1 };
yield return new object[] { 1, 104, 14, 15, 1 };
yield return new object[] { 2, 1500, 228, 241, 1 };
yield return new object[] { 3, 2500, 343, 370, 1 };
yield return new object[] { 4, 3423, 453, 500, 1 };
}
[Test, TestCaseSource("TestCases_Parsing_TextInfo_WordWrapDisabled")]
public void Parsing_TextInfo_WordWrapDisabled(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.NoWrap;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(50, 5);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
public static IEnumerable<object[]> TestCases_Parsing_TextInfo_WordWrapEnabled()
{
yield return new object[] { 0, 22, 4, 5, 1 };
yield return new object[] { 1, 104, 14, 15, 1 };
yield return new object[] { 2, 1500, 228, 241, 13 };
yield return new object[] { 3, 2500, 343, 370, 21 };
yield return new object[] { 4, 3423, 453, 500, 29 };
}
[Test, TestCaseSource("TestCases_Parsing_TextInfo_WordWrapEnabled")]
public void Parsing_TextInfo_WordWrapEnabled(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(100, 50);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
public static IEnumerable<object[]> TestCases_Parsing_TextInfo_AlignmentTopJustified()
{
yield return new object[] { 2, 1500, 228, 241, 13 };
yield return new object[] { 3, 2500, 343, 370, 20 };
yield return new object[] { 4, 3423, 453, 500, 27 };
}
[Test, TestCaseSource("TestCases_Parsing_TextInfo_AlignmentTopJustified")]
public void Parsing_TextInfo_AlignmentTopJustified(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopJustified;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(100, 50);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
public static IEnumerable<object[]> TestCases_Parsing_TextInfo_RichText()
{
yield return new object[] { 5, 59, 8, 9, 1 };
yield return new object[] { 6, 768, 124, 126, 14 };
}
[Test, TestCaseSource("TestCases_Parsing_TextInfo_RichText")]
public void Parsing_TextInfo_RichText(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
public static IEnumerable<object[]> TestCases_MultiLineNewline_OnLastLine_WhenPressedEnter_Caret_ShouldNotGoto_NextLine()
{
yield return new object[] { 1, 1 };
yield return new object[] { 2, 2 };
yield return new object[] { 3, 3 };
yield return new object[] { 4, 4 };
yield return new object[] { 5, 5 };
yield return new object[] { 6, 6 };
}
[Test, TestCaseSource(nameof(TestCases_MultiLineNewline_OnLastLine_WhenPressedEnter_Caret_ShouldNotGoto_NextLine))]
public void MultiLineNewline_OnLastLine_WhenPressedEnter_Caret_ShouldNotGoto_NextLine(int lineLimit,
int expectedLineCount)
{
MultiLineNewline_LineLimit_ExpectedLineCount_Logic(lineLimit, lineLimit, 3);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, expectedLineCount);
}
private void MultiLineNewline_LineLimit_ExpectedLineCount_Logic(int lineLimitValue, int lineLimitApplied,
int extraKeyDownEventCount)
{
GameObject cameraObject = new GameObject("Camera Object", typeof(Camera));
GameObject canvasObject = new GameObject("Canvas Object", typeof(Canvas), typeof(GraphicRaycaster));
canvasObject.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
GameObject inputObject = new GameObject("Input Object", typeof(TMP_InputField));
inputObject.transform.parent = canvasObject.transform;
inputObject.AddComponent<Image>();
TMP_InputField m_InputField = inputObject.GetComponent<TMP_InputField>();
m_InputField.targetGraphic = inputObject.GetComponent<Image>();
m_InputField.textComponent = m_TextComponent;
m_InputField.lineType = TMP_InputField.LineType.MultiLineNewline;
m_InputField.lineLimit = lineLimitValue;
GameObject eventGameObject = new GameObject("Event Object", typeof(EventSystem), typeof(StandaloneInputModule));
Event enterKeyDownEvent = new Event { type = EventType.KeyDown, keyCode = KeyCode.KeypadEnter, modifiers = EventModifiers.None, character = '\n' };
m_InputField.text = "POTUS";
EventSystem.current.SetSelectedGameObject(inputObject);
m_InputField.ActivateInputField();
int count = lineLimitApplied + extraKeyDownEventCount;
while (count > 0)
{
m_InputField.ProcessEvent(enterKeyDownEvent);
m_InputField.ForceLabelUpdate();
count--;
}
m_InputField.textComponent.ForceMeshUpdate();
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(m_InputField);
m_InputField.DeactivateInputField();
GameObject.Destroy(eventGameObject);
GameObject.Destroy(inputObject);
GameObject.Destroy(canvasObject);
GameObject.Destroy(cameraObject);
}
public static IEnumerable<object[]> TestCases_MultiLineNewLine_NegativeOrZeroLineLimit_AddsNewLine()
{
yield return new object[] { 0, 0, 1 };
yield return new object[] { 0, 0, 4 };
yield return new object[] { -1, 0, 2 };
}
[Test, TestCaseSource(nameof(TestCases_MultiLineNewLine_NegativeOrZeroLineLimit_AddsNewLine))]
public void MultiLineNewLine_NegativeOrZeroLineLimit_AddsNewLine(int lineLimitValue, int lineLimitApplied,
int extraKeyDownEventCount)
{
MultiLineNewline_LineLimit_ExpectedLineCount_Logic(lineLimitValue, lineLimitApplied, extraKeyDownEventCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, extraKeyDownEventCount + 1);
}
//[OneTimeTearDown]
//public void Cleanup()
//{
// // Remove TMP Essential Resources if they were imported in the project as a result of running tests.
// if (TMPro_EventManager.temporaryResourcesImported == true)
// {
// string testResourceFolderPath = Path.GetFullPath("Assets/TextMesh Pro");
// if (Directory.Exists(testResourceFolderPath))
// {
// Directory.Delete(testResourceFolderPath);
// File.Delete(Path.GetFullPath("Assets/TextMesh Pro.meta"));
// }
// TMPro_EventManager.temporaryResourcesImported = false;
// }
//}
}
}

View File

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

View File

@@ -0,0 +1,14 @@
{
"name": "Unity.TextMeshPro.Tests",
"references": [
"Unity.TextMeshPro"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"includePlatforms": [],
"excludePlatforms": []
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: bb05cab7d802aa5468f8f2f86840d984
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

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

View File

@@ -0,0 +1,151 @@
using System.Collections;
using System.IO;
using NUnit.Framework;
using UnityEditor;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine;
public class ButtonTests : IPrebuildSetup
{
GameObject m_PrefabRoot;
const string kPrefabPath = "Assets/Resources/ButtonPrefab.prefab";
public void Setup()
{
#if UNITY_EDITOR
var rootGO = new GameObject("rootGo");
var canvasGO = new GameObject("Canvas", typeof(Canvas));
canvasGO.transform.SetParent(rootGO.transform);
var canvas = canvasGO.GetComponent<Canvas>();
canvas.referencePixelsPerUnit = 100;
GameObject eventSystemGO = new GameObject("EventSystem", typeof(EventSystem));
eventSystemGO.transform.SetParent(rootGO.transform);
GameObject TestButtonGO = new GameObject("TestButton", typeof(RectTransform), typeof(TestButton));
TestButtonGO.transform.SetParent(canvasGO.transform);
if (!Directory.Exists("Assets/Resources/"))
Directory.CreateDirectory("Assets/Resources/");
PrefabUtility.SaveAsPrefabAsset(rootGO, kPrefabPath);
GameObject.DestroyImmediate(rootGO);
#endif
}
[SetUp]
public void TestSetup()
{
m_PrefabRoot = Object.Instantiate(Resources.Load("ButtonPrefab")) as GameObject;
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_PrefabRoot);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(kPrefabPath);
#endif
}
[Test]
public void PressShouldCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.True(called);
}
[Test]
public void PressInactiveShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.enabled = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void PressNotInteractableShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.interactable = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void SelectShouldHoldThePreviousStateAfterDisablingAndEnabling()
{
TestButton button = m_PrefabRoot.GetComponentInChildren<TestButton>();
button.onClick.AddListener(() => {
button.Select();
button.enabled = false;
});
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(button.enabled, "Expected button to not be enabled");
button.enabled = true;
Assert.True(button.isStateSelected, "Expected selected state to be true");
}
[Test]
public void SubmitShouldCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(null);
Assert.True(called);
}
[Test]
public void SubmitInactiveShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.enabled = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void SubmitNotInteractableShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.interactable = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[UnityTest]
public IEnumerator SubmitShouldTransitionToPressedStateAndBackToNormal()
{
TestButton button = m_PrefabRoot.GetComponentInChildren<TestButton>();
Assert.True(button.IsTransitionToNormal(0));
button.OnSubmit(null);
Assert.True(button.isStateNormal);
Assert.True(button.IsTransitionToPressed(1));
yield return new WaitWhile(() => button.StateTransitionCount == 2);
// 3rd transition back to normal should have started
Assert.True(button.IsTransitionToNormal(2));
yield return null;
Assert.True(button.isStateNormal);
}
}

View File

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

View File

@@ -0,0 +1,31 @@
using System.Collections.Generic;
using UnityEngine.UI;
class TestButton : Button
{
public bool isStateNormal { get { return currentSelectionState == SelectionState.Normal; } }
public bool isStateHighlighted { get { return currentSelectionState == SelectionState.Highlighted; } }
public bool isStatePressed { get { return currentSelectionState == SelectionState.Pressed; } }
public bool isStateDisabled { get { return currentSelectionState == SelectionState.Disabled; } }
public bool isStateSelected { get { return currentSelectionState == SelectionState.Selected; } }
private bool IsTransitionTo(int index, SelectionState selectionState)
{
return index < m_StateTransitions.Count && m_StateTransitions[index] == selectionState;
}
public bool IsTransitionToNormal(int index) { return IsTransitionTo(index, SelectionState.Normal); }
public bool IsTransitionToHighlighted(int index) { return IsTransitionTo(index, SelectionState.Highlighted); }
public bool IsTransitionToPressed(int index) { return IsTransitionTo(index, SelectionState.Pressed); }
public bool IsTransitionToDisabled(int index) { return IsTransitionTo(index, SelectionState.Disabled); }
private readonly List<SelectionState> m_StateTransitions = new List<SelectionState>();
public int StateTransitionCount { get { return m_StateTransitions.Count; } }
protected override void DoStateTransition(SelectionState state, bool instant)
{
m_StateTransitions.Add(state);
base.DoStateTransition(state, instant);
}
}

View File

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

View File

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

View File

@@ -0,0 +1,9 @@
using UnityEngine;
public class BridgeScriptForRetainingObjects : MonoBehaviour
{
public const string bridgeObjectName = "BridgeGameObject";
public GameObject canvasGO;
public GameObject nestedCanvasGO;
}

View File

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

View File

@@ -0,0 +1,203 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
[TestFixture]
public class CanvasGroupTests
{
GameObject m_CanvasObject;
CanvasGroup m_CanvasGroup;
CanvasRenderer m_ChildCanvasRenderer;
CanvasGroup m_ChildCanvasGroup;
CanvasRenderer m_GrandChildCanvasRenderer;
CanvasGroup m_GrandChildCanvasGroup;
GameObject m_CanvasTwoObject;
CanvasGroup m_CanvasTwoGroup;
CanvasRenderer m_ChildCanvasTwoRenderer;
const float m_CanvasAlpha = 0.25f;
const float m_ChildAlpha = 0.5f;
const float m_GrandChildAlpha = 0.8f;
[SetUp]
public void TestSetup()
{
m_CanvasObject = new GameObject("Canvas", typeof(Canvas));
m_CanvasGroup = m_CanvasObject.AddComponent<CanvasGroup>();
m_CanvasGroup.alpha = m_CanvasAlpha;
var childObject = new GameObject("Child Object", typeof(Image));
childObject.transform.SetParent(m_CanvasObject.transform);
m_ChildCanvasGroup = childObject.AddComponent<CanvasGroup>();
m_ChildCanvasGroup.alpha = m_ChildAlpha;
m_ChildCanvasRenderer = childObject.GetComponent<CanvasRenderer>();
var grandChildObject = new GameObject("Grand Child Object", typeof(Image));
grandChildObject.transform.SetParent(childObject.transform);
m_GrandChildCanvasGroup = grandChildObject.AddComponent<CanvasGroup>();
m_GrandChildCanvasGroup.alpha = m_GrandChildAlpha;
m_GrandChildCanvasRenderer = grandChildObject.GetComponent<CanvasRenderer>();
m_CanvasTwoObject = new GameObject("CanvasTwo", typeof(Canvas));
m_CanvasTwoObject.transform.SetParent(m_CanvasObject.transform);
m_CanvasTwoGroup = m_CanvasTwoObject.AddComponent<CanvasGroup>();
m_CanvasTwoGroup.alpha = m_CanvasAlpha;
var childTwoObject = new GameObject("Child Two Object", typeof(Image));
childTwoObject.transform.SetParent(m_CanvasTwoObject.transform);
m_ChildCanvasTwoRenderer = childTwoObject.GetComponent<CanvasRenderer>();
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasObject);
}
private void SetUpCanvasGroupState()
{
m_CanvasGroup.enabled = false;
m_CanvasGroup.ignoreParentGroups = false;
m_ChildCanvasGroup.enabled = false;
m_ChildCanvasGroup.ignoreParentGroups = false;
m_GrandChildCanvasGroup.enabled = false;
m_GrandChildCanvasGroup.ignoreParentGroups = false;
m_CanvasTwoGroup.enabled = false;
m_CanvasTwoGroup.ignoreParentGroups = false;
}
[Test]
public void EnabledCanvasGroupEffectSelfAndChildrenAlpha()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Enable the child CanvasGroup. It and its children should now have the same alpha value.
m_ChildCanvasGroup.enabled = true;
Assert.AreEqual(m_ChildAlpha, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_ChildAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnACanvasEffectAllChildrenAlpha()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Children under a different nest canvas should also obey the alpha
Assert.AreEqual(1.0f, m_ChildCanvasTwoRenderer.GetInheritedAlpha());
// Enable the Canvas CanvasGroup. All of the Canvas children should now have the same alpha value.
m_CanvasGroup.enabled = true;
Assert.AreEqual(m_CanvasAlpha, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_CanvasAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Children under a different nest canvas should also obey the alpha
Assert.AreEqual(m_CanvasAlpha, m_ChildCanvasTwoRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnLeafChildEffectOnlyThatChild()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Enable the Leaf child CanvasGroup. Only it should have a modified alpha
m_GrandChildCanvasGroup.enabled = true;
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_GrandChildAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnCanvasAndChildMultipleAlphaValuesCorrectly()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Enable the Canvas CanvasGroup. All of the Canvas children should now have the same alpha value.
m_CanvasGroup.enabled = true;
m_ChildCanvasGroup.enabled = true;
Assert.AreEqual(m_CanvasAlpha * m_ChildAlpha, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_CanvasAlpha * m_ChildAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnCanvasAndChildWithChildIgnoringParentGroupMultipleAlphaValuesCorrectly()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Enable the Canvas CanvasGroup. All of the Canvas children should now have the same alpha value.
m_CanvasGroup.enabled = true;
m_ChildCanvasGroup.enabled = true;
m_ChildCanvasGroup.ignoreParentGroups = true;
Assert.AreEqual(m_ChildAlpha, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_ChildAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnCanvasAndChildrenWithAllChildrenIgnoringParentGroupMultipleAlphaValuesCorrectly()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(1.0f, m_GrandChildCanvasRenderer.GetInheritedAlpha());
// Enable the Canvas CanvasGroup. All of the Canvas children should now have the same alpha value.
m_CanvasGroup.enabled = true;
m_ChildCanvasGroup.enabled = true;
m_GrandChildCanvasGroup.enabled = true;
m_ChildCanvasGroup.ignoreParentGroups = true;
m_GrandChildCanvasGroup.ignoreParentGroups = true;
Assert.AreEqual(m_ChildAlpha, m_ChildCanvasRenderer.GetInheritedAlpha());
Assert.AreEqual(m_GrandChildAlpha, m_GrandChildCanvasRenderer.GetInheritedAlpha());
}
[Test]
public void EnabledCanvasGroupOnNestedCanvasIgnoringParentGroupMultipleAlphaValuesCorrectly()
{
// Set up the states of the canvas groups for the tests.
SetUpCanvasGroupState();
// With no enabled CanvasGroup the Alphas should be 1
Assert.AreEqual(1.0f, m_ChildCanvasTwoRenderer.GetInheritedAlpha());
// Enable the Canvas CanvasGroup. All of the Canvas children should now have the same alpha value.
m_CanvasGroup.enabled = true;
m_CanvasTwoGroup.enabled = true;
m_CanvasTwoGroup.ignoreParentGroups = true;
Assert.AreEqual(m_CanvasAlpha, m_ChildCanvasTwoRenderer.GetInheritedAlpha());
}
}

View File

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

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.SceneManagement;
using UnityEditor;
[TestFixture]
public class CanvasResizeCorrectlyForRenderTexture
{
Canvas m_Canvas;
Camera m_Camera;
RenderTexture m_RenderTexture;
[Test]
public void CanvasResizeCorrectly()
{
var cameraGameObject = new GameObject("PreviewCamera", typeof(Camera));
var canvasGameObject = new GameObject("Canvas", typeof(Canvas));
m_Camera = cameraGameObject.GetComponent<Camera>();
m_Canvas = canvasGameObject.GetComponent<Canvas>();
m_Canvas.renderMode = RenderMode.ScreenSpaceCamera;
m_Canvas.worldCamera = m_Camera;
var rectTransform = canvasGameObject.transform as RectTransform;
m_Canvas.updateRectTransformForStandalone = StandaloneRenderResize.Disabled;
m_RenderTexture = new RenderTexture(100, 100, 0);
m_Camera.targetTexture = m_RenderTexture;
m_Camera.Render();
Assert.AreNotEqual(new Vector2(100, 100), rectTransform.sizeDelta);
m_Canvas.updateRectTransformForStandalone = StandaloneRenderResize.Enabled;
m_Camera.Render();
Assert.AreEqual(new Vector2(100, 100), rectTransform.sizeDelta);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_Canvas.gameObject);
GameObject.DestroyImmediate(m_Camera.gameObject);
UnityEngine.Object.DestroyImmediate(m_RenderTexture);
}
}

View File

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

View File

@@ -0,0 +1,54 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
[TestFixture]
[Category("RegressionTest")]
[Description("CoveredBugID = 734299")]
public class CanvasScalerWithChildTextObjectDoesNotCrash
{
GameObject m_CanvasObject;
[SetUp]
public void TestSetup()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Window/General/Game");
#endif
}
[UnityTest]
public IEnumerator CanvasScalerWithChildTextObjectWithTextFontDoesNotCrash()
{
//This adds a Canvas component as well
m_CanvasObject = new GameObject("Canvas");
var canvasScaler = m_CanvasObject.AddComponent<CanvasScaler>();
m_CanvasObject.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceCamera;
//the crash only reproduces if the text component is a child of the game object
//that has the CanvasScaler component and if it has an actual font and text set
var textObject = new GameObject("Text").AddComponent<UnityEngine.UI.Text>();
textObject.font = Font.CreateDynamicFontFromOSFont("Arial", 14);
textObject.text = "New Text";
textObject.transform.SetParent(m_CanvasObject.transform);
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2(1080, 1020);
//The crash happens when setting the referenceResolution to a small value
canvasScaler.referenceResolution = new Vector2(9, 9);
//We need to wait a few milliseconds for the crash to happen, otherwise Debug.Log will
//get executed and the test will pass
yield return new WaitForSeconds(0.1f);
Assert.That(true);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasObject);
}
}

View File

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

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.SceneManagement;
using UnityEditor;
[TestFixture]
public class CanvasSizeCorrectInAwakeAndStart : IPrebuildSetup
{
const string k_SceneName = "CanvasSizeCorrectInAwakeAndStartScene";
GameObject m_CanvasGameObject;
Scene m_InitScene;
public void Setup()
{
#if UNITY_EDITOR
Action codeToExecute = delegate()
{
var canvasGO = new GameObject("CanvasToAddImage", typeof(Canvas));
var imageGO = new GameObject("ImageOnCanvas", typeof(UnityEngine.UI.Image));
imageGO.transform.localPosition = Vector3.one;
imageGO.transform.SetParent(canvasGO.transform);
imageGO.AddComponent<CanvasSizeCorrectInAwakeAndStartScript>();
canvasGO.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
imageGO.SetActive(false);
};
CreateSceneUtility.CreateScene(k_SceneName, codeToExecute);
#endif
}
[SetUp]
public void TestSetup()
{
m_InitScene = SceneManager.GetActiveScene();
}
[UnityTest]
public IEnumerator CanvasSizeIsCorrectInAwakeAndStart()
{
AsyncOperation operation = SceneManager.LoadSceneAsync(k_SceneName, LoadSceneMode.Additive);
yield return operation;
SceneManager.SetActiveScene(SceneManager.GetSceneByName(k_SceneName));
m_CanvasGameObject = GameObject.Find("CanvasToAddImage");
var imageGO = m_CanvasGameObject.transform.Find("ImageOnCanvas");
imageGO.gameObject.SetActive(true);
var component = imageGO.GetComponent<CanvasSizeCorrectInAwakeAndStartScript>();
yield return new WaitUntil(() => component.isAwakeCalled && component.isStartCalled);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasGameObject);
SceneManager.SetActiveScene(m_InitScene);
SceneManager.UnloadSceneAsync(k_SceneName);
#if UNITY_EDITOR
AssetDatabase.DeleteAsset("Assets/" + k_SceneName + ".unity");
#endif
}
}

View File

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

View File

@@ -0,0 +1,21 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools.Utils;
public class CanvasSizeCorrectInAwakeAndStartScript : MonoBehaviour
{
public bool isStartCalled { get; private set; }
public bool isAwakeCalled { get; private set; }
protected void Awake()
{
Assert.That(transform.position, Is.Not.EqualTo(Vector3.zero).Using(new Vector3EqualityComparer(0.0f)));
isAwakeCalled = true;
}
protected void Start()
{
Assert.That(transform.position, Is.Not.EqualTo(Vector3.zero).Using(new Vector3EqualityComparer(0.0f)));
isStartCalled = true;
}
}

View File

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

View File

@@ -0,0 +1,85 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.TestTools.Utils;
[TestFixture]
public class CheckMeshColorsAndColors32Match
{
GameObject m_CanvasGO;
GameObject m_ColorMeshGO;
GameObject m_Color32MeshGO;
Texture2D m_ScreenTexture;
[SetUp]
public void TestSetup()
{
// Create Canvas
m_CanvasGO = new GameObject("Canvas");
Canvas canvas = m_CanvasGO.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
// Create Color UI GameObject
m_ColorMeshGO = new GameObject("ColorMesh");
CanvasRenderer colorMeshCanvasRenderer = m_ColorMeshGO.AddComponent<CanvasRenderer>();
RectTransform colorMeshRectTransform = m_ColorMeshGO.AddComponent<RectTransform>();
colorMeshRectTransform.pivot = colorMeshRectTransform.anchorMin = colorMeshRectTransform.anchorMax = Vector2.zero;
m_ColorMeshGO.transform.SetParent(m_CanvasGO.transform);
// Create Color32 UI GameObject
m_Color32MeshGO = new GameObject("Color32Mesh");
CanvasRenderer color32MeshCanvasRenderer = m_Color32MeshGO.AddComponent<CanvasRenderer>();
RectTransform color32MeshRectTransform = m_Color32MeshGO.AddComponent<RectTransform>();
color32MeshRectTransform.pivot = color32MeshRectTransform.anchorMin = color32MeshRectTransform.anchorMax = Vector2.zero;
m_Color32MeshGO.transform.SetParent(m_CanvasGO.transform);
Material material = new Material(Shader.Find("UI/Default"));
// Setup Color mesh and add it to Color CanvasRenderer
Mesh meshColor = new Mesh();
meshColor.vertices = new Vector3[3] { new Vector3(0, 0, 0), new Vector3(0, 10, 0), new Vector3(10, 0, 0) };
meshColor.triangles = new int[3] { 0, 1, 2 };
meshColor.normals = new Vector3[3] { Vector3.zero, Vector3.zero, Vector3.zero };
meshColor.colors = new Color[3] { Color.white, Color.white, Color.white };
meshColor.uv = new Vector2[3] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 0) };
colorMeshCanvasRenderer.SetMesh(meshColor);
colorMeshCanvasRenderer.SetMaterial(material, null);
// Setup Color32 mesh and add it to Color32 CanvasRenderer
Mesh meshColor32 = new Mesh();
meshColor32.vertices = new Vector3[3] { new Vector3(10, 0, 0), new Vector3(10, 10, 0), new Vector3(20, 0, 0) };
meshColor32.triangles = new int[3] { 0, 1, 2 };
meshColor32.normals = new Vector3[3] { Vector3.zero, Vector3.zero, Vector3.zero };
meshColor32.colors32 = new Color32[3] { Color.white, Color.white, Color.white };
meshColor32.uv = new Vector2[3] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 0) };
color32MeshCanvasRenderer.SetMesh(meshColor32);
color32MeshCanvasRenderer.SetMaterial(material, null);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasGO);
GameObject.DestroyImmediate(m_ScreenTexture);
}
[Ignore("UnityTest yielded WaitForEndOfFrame, which is not evoked in batchmode.")]
[UnityTest]
public IEnumerator CheckMeshColorsAndColors32Matches()
{
yield return new WaitForEndOfFrame();
// Create a Texture2D
m_ScreenTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
m_ScreenTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
m_ScreenTexture.Apply();
Color screenPixelColorForMeshColor = m_ScreenTexture.GetPixel(1, 0);
Color screenPixelColorForMesh32Color = m_ScreenTexture.GetPixel(11, 0);
Assert.That(screenPixelColorForMesh32Color, Is.EqualTo(screenPixelColorForMeshColor).Using(new ColorEqualityComparer(0.0f)), "UI Mesh with Colors does not match UI Mesh with Colors32");
}
}

View File

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

View File

@@ -0,0 +1,74 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
[TestFixture]
[UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor })]
[Category("RegressionTest")]
[Description("CoveredBugID = 904415")]
public class CoroutineWorksIfUIObjectIsAttached
{
GameObject m_CanvasMaster;
GameObject m_ImageObject;
[SetUp]
public void TestSetup()
{
m_CanvasMaster = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
m_ImageObject = new GameObject("Image", typeof(Image));
m_ImageObject.SetActive(false);
}
[UnityTest]
public IEnumerator CoroutineWorksOnAttachingUIObject()
{
// Generating Basic scene
m_CanvasMaster.AddComponent<CoroutineObject>();
yield return null;
m_ImageObject.transform.SetParent(m_CanvasMaster.transform);
m_ImageObject.AddComponent<BugObject>();
m_ImageObject.SetActive(true);
yield return null;
yield return null;
yield return null;
Assert.That(m_CanvasMaster.GetComponent<CoroutineObject>().coroutineCount, Is.GreaterThan(1), "The Coroutine wasn't supposed to stop but continue to run, something made it stopped");
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasMaster);
GameObject.DestroyImmediate(m_ImageObject);
}
}
public class BugObject : MonoBehaviour
{
void Awake()
{
GameObject newObject = new GameObject("NewGameObjectThatTriggersBug");
newObject.transform.SetParent(transform);
newObject.AddComponent<Text>();
}
}
public class CoroutineObject : MonoBehaviour
{
public int coroutineCount { get; private set; }
public IEnumerator Start()
{
// This coroutine should not stop and continue adding to the timer
while (true)
{
coroutineCount++;
yield return null;
}
}
}

View File

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

View File

@@ -0,0 +1,25 @@
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
class CreateSceneUtility
{
public static void CreateScene(string sceneName, Action delegateToExecute)
{
#if UNITY_EDITOR
string scenePath = "Assets/" + sceneName + ".unity";
var initScene = SceneManager.GetActiveScene();
var list = UnityEditor.EditorBuildSettings.scenes.ToList();
var newScene = UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects, UnityEditor.SceneManagement.NewSceneMode.Additive);
GameObject.DestroyImmediate(Camera.main.GetComponent<AudioListener>());
delegateToExecute();
UnityEditor.SceneManagement.EditorSceneManager.SaveScene(newScene, scenePath);
UnityEditor.SceneManagement.EditorSceneManager.UnloadSceneAsync(newScene);
list.Add(new UnityEditor.EditorBuildSettingsScene(scenePath, true));
UnityEditor.EditorBuildSettings.scenes = list.ToArray();
SceneManager.SetActiveScene(initScene);
#endif
}
}

View File

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

View File

@@ -0,0 +1,102 @@
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEditor;
public class NestedCanvas : IPrebuildSetup
{
Object m_GO1;
Object m_GO2;
const string kPrefabPath = "Assets/Resources/NestedCanvasPrefab.prefab";
public void Setup()
{
#if UNITY_EDITOR
var rootGO = new GameObject("RootGO");
var rootCanvasGO = new GameObject("Canvas", typeof(Canvas), typeof(CanvasGroup));
rootCanvasGO.transform.SetParent(rootGO.transform);
var nestedCanvas = new GameObject("Nested Canvas", typeof(Canvas), typeof(Image));
nestedCanvas.transform.SetParent(rootCanvasGO.transform);
var nestedCanvasCamera = new GameObject("Nested Canvas Camera", typeof(Camera));
nestedCanvasCamera.transform.SetParent(rootCanvasGO.transform);
var rootCanvas = rootCanvasGO.GetComponent<Canvas>();
rootCanvas.renderMode = RenderMode.WorldSpace;
rootCanvas.worldCamera = nestedCanvasCamera.GetComponent<Camera>();
if (!Directory.Exists("Assets/Resources/"))
Directory.CreateDirectory("Assets/Resources/");
UnityEditor.PrefabUtility.SaveAsPrefabAsset(rootGO, kPrefabPath);
GameObject.DestroyImmediate(rootGO);
#endif
}
[UnityTest]
[Description("[UI] Button does not interact after nested canvas is used(case 892913)")]
public IEnumerator WorldCanvas_CanFindCameraAfterDisablingAndEnablingRootCanvas()
{
m_GO1 = Object.Instantiate(Resources.Load("NestedCanvasPrefab"));
yield return null;
var nestedCanvasGo = GameObject.Find("Nested Canvas");
var nestedCanvas = nestedCanvasGo.GetComponent<Canvas>();
Assert.IsNotNull(nestedCanvas.worldCamera, "Expected the nested canvas worldCamera to NOT be null after loading the scene.");
nestedCanvasGo.transform.parent.gameObject.SetActive(false);
nestedCanvasGo.transform.parent.gameObject.SetActive(true);
Assert.IsNotNull(nestedCanvas.worldCamera, "Expected the nested canvas worldCamera to NOT be null after the parent canvas has been re-enabled.");
}
[UnityTest]
public IEnumerator WorldCanvas_CanFindTheSameCameraAfterDisablingAndEnablingRootCanvas()
{
m_GO2 = Object.Instantiate(Resources.Load("NestedCanvasPrefab"));
yield return null;
var nestedCanvasGo = GameObject.Find("Nested Canvas");
var nestedCanvas = nestedCanvasGo.GetComponent<Canvas>();
var worldCamera = nestedCanvas.worldCamera;
nestedCanvasGo.transform.parent.gameObject.SetActive(false);
nestedCanvasGo.transform.parent.gameObject.SetActive(true);
Assert.AreEqual(worldCamera, nestedCanvas.worldCamera, "Expected the same world camera to be returned after the root canvas was disabled and then re-enabled.");
}
[UnityTest]
public IEnumerator NestedCanvasHasProperInheritedAlpha()
{
GameObject root = (GameObject)Object.Instantiate(Resources.Load("NestedCanvasPrefab"));
CanvasGroup group = root.GetComponentInChildren<CanvasGroup>();
Image image = root.GetComponentInChildren<Image>();
group.alpha = 0.5f;
yield return null;
Assert.True(image.canvasRenderer.GetInheritedAlpha() == 0.5f);
GameObject.DestroyImmediate(root);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_GO1);
GameObject.DestroyImmediate(m_GO2);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(kPrefabPath);
#endif
}
}

View File

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

View File

@@ -0,0 +1,57 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
public class NestedCanvasMaintainsCorrectSize : IPrebuildSetup
{
BridgeScriptForRetainingObjects m_BridgeComponent;
public void Setup()
{
#if UNITY_EDITOR
var canvasGO = new GameObject("Canvas", typeof(Canvas));
canvasGO.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
var nestedCanvasGO = new GameObject("NestedCanvas", typeof(Canvas));
nestedCanvasGO.transform.SetParent(canvasGO.transform);
var rectTransform = (RectTransform)nestedCanvasGO.transform;
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.anchoredPosition = Vector2.zero;
rectTransform.sizeDelta = new Vector2(-20f, -20f);
var bridgeObject = GameObject.Find(BridgeScriptForRetainingObjects.bridgeObjectName) ?? new GameObject(BridgeScriptForRetainingObjects.bridgeObjectName);
var component = bridgeObject.GetComponent<BridgeScriptForRetainingObjects>() ?? bridgeObject.AddComponent<BridgeScriptForRetainingObjects>();
component.canvasGO = canvasGO;
component.nestedCanvasGO = nestedCanvasGO;
canvasGO.SetActive(false);
nestedCanvasGO.SetActive(false);
#endif
}
[SetUp]
public void TestSetup()
{
m_BridgeComponent = GameObject.Find(BridgeScriptForRetainingObjects.bridgeObjectName).GetComponent<BridgeScriptForRetainingObjects>();
m_BridgeComponent.canvasGO.SetActive(true);
m_BridgeComponent.nestedCanvasGO.SetActive(true);
}
[Test]
public void NestedCanvasMaintainsCorrectSizeAtGameStart()
{
var rectTransform = (RectTransform)m_BridgeComponent.nestedCanvasGO.transform;
Assert.That(rectTransform.anchoredPosition, Is.EqualTo(Vector2.zero));
Assert.That(rectTransform.sizeDelta, Is.EqualTo(new Vector2(-20f, -20f)));
Assert.That(rectTransform.anchorMin, Is.EqualTo(Vector2.zero));
Assert.That(rectTransform.anchorMax, Is.EqualTo(Vector2.one));
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_BridgeComponent.canvasGO);
}
}

View File

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

View File

@@ -0,0 +1,61 @@
using System;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.Profiling;
using UnityEngine.SceneManagement;
using UnityEditor;
[TestFixture]
[UnityPlatform(include = new RuntimePlatform[] { RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor })]
[Category("RegressionTest")]
[Description("CoveredBugID = 883807, CoveredBugDescription = \"Object::GetInstanceID crash when trying to switch canvas\"")]
public class NoActiveCameraInSceneDoesNotCrashEditor : IPrebuildSetup
{
Scene m_InitScene;
const string k_SceneName = "NoActiveCameraInSceneDoesNotCrashEditorScene";
public void Setup()
{
#if UNITY_EDITOR
Action codeToExecute = delegate()
{
UnityEditor.EditorApplication.ExecuteMenuItem("GameObject/UI/Legacy/Button");
};
CreateSceneUtility.CreateScene(k_SceneName, codeToExecute);
#endif
}
[SetUp]
public void TestSetup()
{
m_InitScene = SceneManager.GetActiveScene();
}
[UnityTest]
public IEnumerator EditorShouldNotCrashWithoutActiveCamera()
{
AsyncOperation operationResult = SceneManager.LoadSceneAsync(k_SceneName, LoadSceneMode.Additive);
yield return operationResult;
SceneManager.SetActiveScene(SceneManager.GetSceneByName(k_SceneName));
Profiler.enabled = true;
Camera.main.gameObject.SetActive(false);
yield return new WaitForSeconds(0.1f);
Assert.That(Profiler.enabled, Is.True, "Expected the profiler to be enabled. Unable to test if the profiler will crash the editor if it is not enabled.");
}
[TearDown]
public void TearDown()
{
SceneManager.SetActiveScene(m_InitScene);
SceneManager.UnloadSceneAsync(k_SceneName);
#if UNITY_EDITOR
AssetDatabase.DeleteAsset("Assets/" + k_SceneName + ".unity");
#endif
}
}

View File

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

View File

@@ -0,0 +1,47 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
namespace Graphics
{
[Category("RegressionTest")]
[Description("CoveredBugID = 1395695, CoveredBugDescription = \"RectMask2D hides all content when parented from other display to first dislpay in the Game view window\"")]
public class RectMask2DReparentedToDifferentCanvas
{
GameObject m_GameObjectA;
GameObject m_GameObjectB;
Canvas m_CanvasA;
Canvas m_CanvasB;
RectMask2D m_Mask;
[SetUp]
public void TestSetup()
{
m_GameObjectA = new GameObject("Canvas A");
m_GameObjectB = new GameObject("Canvas B");
m_CanvasA = m_GameObjectA.AddComponent<Canvas>();
m_CanvasB = m_GameObjectB.AddComponent<Canvas>();
var rectMaskGameObject = new GameObject("RectMask2D");
m_Mask = rectMaskGameObject.AddComponent<RectMask2D>();
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_Mask.gameObject);
Object.DestroyImmediate(m_GameObjectA);
Object.DestroyImmediate(m_GameObjectB);
}
[Test]
public void ReparentingRectMask2D_UpdatesCanvas()
{
m_Mask.transform.SetParent(m_GameObjectA.transform);
Assert.AreSame(m_CanvasA, m_Mask.Canvas);
m_Mask.transform.SetParent(m_GameObjectB.transform);
Assert.AreSame(m_CanvasB, m_Mask.Canvas, "Expected Canvas to be updated after parent changed.");
}
}
}

View File

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

View File

@@ -0,0 +1,63 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
namespace Graphics
{
[TestFixture]
[Category("RegressionTest")]
[Description(
"CoveredBugID = 782957, CoveredBugDescription = \"Some element from scroll view are invisible when they're masked with RectMask2D and sub-canvases\"")]
public class RectMask2DWithNestedCanvasCullsUsingCorrectCanvasRect
{
GameObject m_RootCanvasGO;
GameObject m_MaskGO;
GameObject m_ImageGO;
[SetUp]
public void TestSetup()
{
m_RootCanvasGO = new GameObject("Canvas");
m_MaskGO = new GameObject("Mask", typeof(RectMask2D));
m_ImageGO = new GameObject("Image");
}
[UnityTest]
public IEnumerator RectMask2DShouldNotCullImagesWithCanvas()
{
//Root Canvas
var canvas = m_RootCanvasGO.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
// Rectmaskk2D
var maskRect = m_MaskGO.GetComponent<RectTransform>();
maskRect.sizeDelta = new Vector2(200, 200);
// Our image that will be in the RectMask2D
var image = m_ImageGO.AddComponent<Image>();
var imageRenderer = m_ImageGO.GetComponent<CanvasRenderer>();
var imageRect = m_ImageGO.GetComponent<RectTransform>();
m_ImageGO.AddComponent<Canvas>();
imageRect.sizeDelta = new Vector2(10, 10);
m_MaskGO.transform.SetParent(canvas.transform);
image.transform.SetParent(m_MaskGO.transform);
imageRect.position = maskRect.position = Vector3.zero;
yield return new WaitForSeconds(0.1f);
Assert.That(imageRenderer.cull, Is.False,
"Expected image(with canvas) to not be culled by the RectMask2D but it was.");
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_RootCanvasGO);
GameObject.DestroyImmediate(m_MaskGO);
GameObject.DestroyImmediate(m_ImageGO);
}
}
}

View File

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

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEditor;
[TestFixture]
public class RectTransformValidAfterEnable : IPrebuildSetup
{
const string kSceneName = "DisabledCanvasScene";
const string kGameObjectName = "DisabledCanvas";
public void Setup()
{
#if UNITY_EDITOR
Action codeToExecute = delegate()
{
var canvasGameObject = new GameObject(kGameObjectName, typeof(Canvas));
canvasGameObject.SetActive(false);
canvasGameObject.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
canvasGameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 0);
canvasGameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
CanvasScaler canvasScaler = canvasGameObject.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2(1024, 768);
};
CreateSceneUtility.CreateScene(kSceneName, codeToExecute);
#endif
}
[Ignore("UnityTest yielded WaitForEndOfFrame, which is not evoked in batchmode.")]
[UnityTest]
public IEnumerator CheckRectTransformValidAfterEnable()
{
AsyncOperation operation = SceneManager.LoadSceneAsync(kSceneName, LoadSceneMode.Additive);
yield return operation;
Scene scene = SceneManager.GetSceneByName(kSceneName);
GameObject[] gameObjects = scene.GetRootGameObjects();
GameObject canvasGameObject = null;
foreach (GameObject gameObject in gameObjects)
{
if (gameObject.name == kGameObjectName)
{
canvasGameObject = gameObject;
break;
}
}
Assert.IsNotNull(canvasGameObject);
RectTransform rectTransform = canvasGameObject.GetComponent<RectTransform>();
canvasGameObject.SetActive(true);
yield return new WaitForEndOfFrame();
Rect rect = rectTransform.rect;
Assert.Greater(rect.width, 0);
Assert.Greater(rect.height, 0);
operation = SceneManager.UnloadSceneAsync(kSceneName);
yield return operation;
}
[TearDown]
public void TearDown()
{
//Manually add Assets/ and .unity as CreateSceneUtility does that for you.
#if UNITY_EDITOR
AssetDatabase.DeleteAsset("Assets/" + kSceneName + ".unity");
#endif
}
}

View File

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

View File

@@ -0,0 +1,76 @@
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using System.Linq;
public class RectangleContainsScreenPointTest : MonoBehaviour
{
RectTransform m_RectTransform;
Camera m_MainCamera;
GameObject m_CanvasObject;
GameObject m_RectObject;
[SetUp]
public void Setup()
{
m_MainCamera = new GameObject("MainCamera").AddComponent<Camera>();
m_MainCamera.transform.position = new Vector3(0, 1, -10);
m_MainCamera.depth = -1;
m_CanvasObject = new GameObject("Canvas");
Canvas m_canvas = m_CanvasObject.AddComponent<Canvas>();
m_canvas.transform.localPosition = new Vector3(0, 1, 90);
m_canvas.renderMode = RenderMode.ScreenSpaceCamera;
m_canvas.worldCamera = m_MainCamera;
m_RectObject = new GameObject("RectTransformObject");
m_RectTransform = m_RectObject.AddComponent<RectTransform>();
m_RectTransform.SetParent(m_CanvasObject.transform, false);
}
[TearDown]
public void TearDown()
{
Destroy(m_MainCamera.gameObject);
Destroy(m_CanvasObject);
Destroy(m_RectObject);
Destroy(m_RectTransform);
}
[Test]
public void RectangleContainsScreenPoint_ReturnsTrue_ForAllPointsInTheRectangle()
{
var fourCourners = new Vector3[4];
m_RectTransform.GetWorldCorners(fourCourners);
var worldCorners = fourCourners
.Select(p => m_MainCamera.WorldToScreenPoint(p))
.ToArray();
var minValue = new Vector2(
x: worldCorners.Min(p => p.x),
y: worldCorners.Min(p => p.y));
var maxValue = new Vector2(
x: worldCorners.Max(p => p.x),
y: worldCorners.Max(p => p.y));
var steps = 10000;
bool ErrorHit = false;
for (float i = 0; i < steps; i++)
{
var point = Vector2.Lerp(minValue, maxValue, i / steps);
if (!RectTransformUtility.RectangleContainsScreenPoint(m_RectTransform, point, m_MainCamera))
{
ErrorHit = true;
Assert.Fail("Rectangle does not Contains ScreenPoint");
}
}
if (!ErrorHit)
{
Assert.Pass();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 08a8587e5f07fb64f88a0cbe2ebe327e

View File

@@ -0,0 +1,84 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
[TestFixture]
[Category("RegressionTest")]
[Description("Case 723062")]
public class SiblingOrderChangesLayout
{
GameObject m_CanvasGO;
GameObject m_ParentGO;
GameObject m_Child1GO;
GameObject m_Child2GO;
[SetUp]
public void TestSetup()
{
m_CanvasGO = new GameObject("Canvas", typeof(Canvas));
m_ParentGO = new GameObject("ParentRenderer");
m_Child1GO = CreateTextObject("ChildRenderer1");
m_Child2GO = CreateTextObject("ChildRenderer2");
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExecuteMenuItem("Window/General/Game");
#endif
}
[Ignore("UnityTest yielded WaitForEndOfFrame, which is not evoked in batchmode.")]
[UnityTest]
public IEnumerator ReorderingSiblingChangesLayout()
{
m_ParentGO.transform.SetParent(m_CanvasGO.transform);
m_Child1GO.transform.SetParent(m_ParentGO.transform);
m_Child2GO.transform.SetParent(m_ParentGO.transform);
m_ParentGO.AddComponent<CanvasRenderer>();
m_ParentGO.AddComponent<RectTransform>();
m_ParentGO.AddComponent<VerticalLayoutGroup>();
m_ParentGO.AddComponent<ContentSizeFitter>();
yield return new WaitForEndOfFrame();
Vector2 child1Pos = m_Child1GO.GetComponent<RectTransform>().anchoredPosition;
Vector2 child2Pos = m_Child2GO.GetComponent<RectTransform>().anchoredPosition;
Assert.That(child1Pos, Is.Not.EqualTo(child2Pos));
Assert.That(m_Child1GO.GetComponent<CanvasRenderer>().hasMoved, Is.False, "CanvasRenderer.hasMoved should be false");
m_Child2GO.transform.SetAsFirstSibling();
Canvas.ForceUpdateCanvases();
Assert.That(m_Child1GO.GetComponent<CanvasRenderer>().hasMoved, Is.True, "CanvasRenderer.hasMoved should be true");
Vector2 newChild1Pos = m_Child1GO.GetComponent<RectTransform>().anchoredPosition;
Vector2 newChild2Pos = m_Child2GO.GetComponent<RectTransform>().anchoredPosition;
Assert.That(newChild1Pos, Is.EqualTo(child2Pos), "Child1 should have moved to Child2's position");
Assert.That(newChild2Pos, Is.EqualTo(child1Pos), "Child2 should have moved to Child1's position");
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasGO);
}
// Factory method for creating UI text objects taken from the original bug repro scene:
private GameObject CreateTextObject(string name)
{
GameObject outputTextGameObject = new GameObject("OutputContent", typeof(CanvasRenderer));
RectTransform outputTextTransform = outputTextGameObject.AddComponent<RectTransform>();
outputTextTransform.pivot = new Vector2(0.5f, 0);
outputTextTransform.anchorMin = Vector2.zero;
outputTextTransform.anchorMax = new Vector2(1, 0);
outputTextTransform.anchoredPosition = Vector2.zero;
outputTextTransform.sizeDelta = Vector2.zero;
Text outputText = outputTextGameObject.AddComponent<Text>();
outputText.text = "Hello World!";
outputTextGameObject.name = name;
return outputTextGameObject;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,162 @@
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.IO;
using UnityEditor;
using System.Collections.Generic;
public class DropdownTests : IPrebuildSetup
{
GameObject m_PrefabRoot;
GameObject m_CameraGO;
const string kPrefabPath = "Assets/Resources/DropdownPrefab.prefab";
public void Setup()
{
#if UNITY_EDITOR
var rootGO = new GameObject("rootGo");
var canvasGO = new GameObject("Canvas", typeof(Canvas));
var canvas = canvasGO.GetComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
canvasGO.transform.SetParent(rootGO.transform);
var dropdownGO = new GameObject("Dropdown", typeof(RectTransform), typeof(Dropdown));
var dropdownTransform = dropdownGO.GetComponent<RectTransform>();
dropdownTransform.SetParent(canvas.transform);
dropdownTransform.anchoredPosition = Vector2.zero;
var dropdown = dropdownGO.GetComponent<Dropdown>();
var templateGO = new GameObject("Template", typeof(RectTransform));
templateGO.SetActive(false);
var templateTransform = templateGO.GetComponent<RectTransform>();
templateTransform.SetParent(dropdownTransform);
var itemGo = new GameObject("Item", typeof(RectTransform), typeof(Toggle));
itemGo.transform.SetParent(templateTransform);
dropdown.template = templateTransform;
if (!Directory.Exists("Assets/Resources/"))
Directory.CreateDirectory("Assets/Resources/");
PrefabUtility.SaveAsPrefabAsset(rootGO, kPrefabPath);
GameObject.DestroyImmediate(rootGO);
// add a custom sorting layer before test. It doesn't seem to be serialized so no need to remove it after test
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty sortingLayers = tagManager.FindProperty("m_SortingLayers");
sortingLayers.InsertArrayElementAtIndex(sortingLayers.arraySize);
var arrayElement = sortingLayers.GetArrayElementAtIndex(sortingLayers.arraySize - 1);
foreach (SerializedProperty a in arrayElement)
{
switch (a.name)
{
case "name":
a.stringValue = "test layer";
break;
case "uniqueID":
a.intValue = 314159265;
break;
case "locked":
a.boolValue = false;
break;
}
}
tagManager.ApplyModifiedProperties();
#endif
}
[SetUp]
public void TestSetup()
{
m_PrefabRoot = Object.Instantiate(Resources.Load("DropdownPrefab")) as GameObject;
m_CameraGO = new GameObject("Camera", typeof(Camera));
}
// test for case 958281 - [UI] Dropdown list does not copy the parent canvas layer when the panel is opened
[UnityTest]
public IEnumerator Dropdown_Canvas()
{
var dropdown = m_PrefabRoot.GetComponentInChildren<Dropdown>();
var rootCanvas = m_PrefabRoot.GetComponentInChildren<Canvas>();
rootCanvas.sortingLayerName = "test layer";
dropdown.Show();
yield return null;
var dropdownList = dropdown.transform.Find("Dropdown List");
var dropdownListCanvas = dropdownList.GetComponentInChildren<Canvas>();
Assert.AreEqual(rootCanvas.sortingLayerID, dropdownListCanvas.sortingLayerID, "Sorting layers should match");
}
// test for case 1343542 - [UI] Child Canvas' Sorting Layer is changed to the same value as the parent
[UnityTest]
public IEnumerator Dropdown_Canvas_Already_Exists()
{
var dropdown = m_PrefabRoot.GetComponentInChildren<Dropdown>();
var rootCanvas = m_PrefabRoot.GetComponentInChildren<Canvas>();
var templateCanvas = dropdown.transform.Find("Template").gameObject.AddComponent<Canvas>();
templateCanvas.overrideSorting = true;
templateCanvas.sortingLayerName = "test layer";
dropdown.Show();
yield return null;
var dropdownList = dropdown.transform.Find("Dropdown List");
var dropdownListCanvas = dropdownList.GetComponentInChildren<Canvas>();
Assert.AreNotEqual(rootCanvas.sortingLayerName, dropdownListCanvas.sortingLayerName, "Sorting layers should not match");
}
// test for case 935649 - open dropdown menus become unresponsive when disabled and reenabled
[UnityTest]
public IEnumerator Dropdown_Disable()
{
var dropdown = m_PrefabRoot.GetComponentInChildren<Dropdown>();
dropdown.Show();
dropdown.gameObject.SetActive(false);
yield return null;
var dropdownList = dropdown.transform.Find("Dropdown List");
Assert.IsNull(dropdownList);
}
[UnityTest]
public IEnumerator Dropdown_ResetAndClear()
{
var options = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var dropdown = m_PrefabRoot.GetComponentInChildren<Dropdown>();
// generate a first dropdown
dropdown.ClearOptions();
dropdown.AddOptions(options);
dropdown.value = 3;
yield return null;
// clear it and generate a new one
dropdown.ClearOptions();
yield return null;
// check is the value is 0
Assert.IsTrue(dropdown.value == 0);
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_PrefabRoot);
GameObject.DestroyImmediate(m_CameraGO);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(kPrefabPath);
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty sortingLayers = tagManager.FindProperty("m_SortingLayers");
sortingLayers.DeleteArrayElementAtIndex(sortingLayers.arraySize);
tagManager.ApplyModifiedProperties();
#endif
}
}

Some files were not shown because too many files have changed in this diff Show More