Commit 0f3088bc authored by gaorui's avatar gaorui
Browse files

Initial commit

parents
fileFormatVersion: 2
guid: d736ce056cf444ca96e424f4d9c42b76
timeCreated: 1480416736
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System;
namespace TMPro
{
public class TMP_TextEventHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[Serializable]
public class CharacterSelectionEvent : UnityEvent<char, int> { }
[Serializable]
public class SpriteSelectionEvent : UnityEvent<char, int> { }
[Serializable]
public class WordSelectionEvent : UnityEvent<string, int, int> { }
[Serializable]
public class LineSelectionEvent : UnityEvent<string, int, int> { }
[Serializable]
public class LinkSelectionEvent : UnityEvent<string, string, int> { }
/// <summary>
/// Event delegate triggered when pointer is over a character.
/// </summary>
public CharacterSelectionEvent onCharacterSelection
{
get { return m_OnCharacterSelection; }
set { m_OnCharacterSelection = value; }
}
[SerializeField]
private CharacterSelectionEvent m_OnCharacterSelection = new CharacterSelectionEvent();
/// <summary>
/// Event delegate triggered when pointer is over a sprite.
/// </summary>
public SpriteSelectionEvent onSpriteSelection
{
get { return m_OnSpriteSelection; }
set { m_OnSpriteSelection = value; }
}
[SerializeField]
private SpriteSelectionEvent m_OnSpriteSelection = new SpriteSelectionEvent();
/// <summary>
/// Event delegate triggered when pointer is over a word.
/// </summary>
public WordSelectionEvent onWordSelection
{
get { return m_OnWordSelection; }
set { m_OnWordSelection = value; }
}
[SerializeField]
private WordSelectionEvent m_OnWordSelection = new WordSelectionEvent();
/// <summary>
/// Event delegate triggered when pointer is over a line.
/// </summary>
public LineSelectionEvent onLineSelection
{
get { return m_OnLineSelection; }
set { m_OnLineSelection = value; }
}
[SerializeField]
private LineSelectionEvent m_OnLineSelection = new LineSelectionEvent();
/// <summary>
/// Event delegate triggered when pointer is over a link.
/// </summary>
public LinkSelectionEvent onLinkSelection
{
get { return m_OnLinkSelection; }
set { m_OnLinkSelection = value; }
}
[SerializeField]
private LinkSelectionEvent m_OnLinkSelection = new LinkSelectionEvent();
private TMP_Text m_TextComponent;
private Camera m_Camera;
private Canvas m_Canvas;
private int m_selectedLink = -1;
private int m_lastCharIndex = -1;
private int m_lastWordIndex = -1;
private int m_lastLineIndex = -1;
void Awake()
{
// Get a reference to the text component.
m_TextComponent = gameObject.GetComponent<TMP_Text>();
// Get a reference to the camera rendering the text taking into consideration the text component type.
if (m_TextComponent.GetType() == typeof(TextMeshProUGUI))
{
m_Canvas = gameObject.GetComponentInParent<Canvas>();
if (m_Canvas != null)
{
if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
m_Camera = null;
else
m_Camera = m_Canvas.worldCamera;
}
}
else
{
m_Camera = Camera.main;
}
}
void LateUpdate()
{
if (TMP_TextUtilities.IsIntersectingRectTransform(m_TextComponent.rectTransform, Input.mousePosition, m_Camera))
{
#region Example of Character or Sprite Selection
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextComponent, Input.mousePosition, m_Camera, true);
if (charIndex != -1 && charIndex != m_lastCharIndex)
{
m_lastCharIndex = charIndex;
TMP_TextElementType elementType = m_TextComponent.textInfo.characterInfo[charIndex].elementType;
// Send event to any event listeners depending on whether it is a character or sprite.
if (elementType == TMP_TextElementType.Character)
SendOnCharacterSelection(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
else if (elementType == TMP_TextElementType.Sprite)
SendOnSpriteSelection(m_TextComponent.textInfo.characterInfo[charIndex].character, charIndex);
}
#endregion
#region Example of Word Selection
// Check if Mouse intersects any words and if so assign a random color to that word.
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, Input.mousePosition, m_Camera);
if (wordIndex != -1 && wordIndex != m_lastWordIndex)
{
m_lastWordIndex = wordIndex;
// Get the information about the selected word.
TMP_WordInfo wInfo = m_TextComponent.textInfo.wordInfo[wordIndex];
// Send the event to any listeners.
SendOnWordSelection(wInfo.GetWord(), wInfo.firstCharacterIndex, wInfo.characterCount);
}
#endregion
#region Example of Line Selection
// Check if Mouse intersects any words and if so assign a random color to that word.
int lineIndex = TMP_TextUtilities.FindIntersectingLine(m_TextComponent, Input.mousePosition, m_Camera);
if (lineIndex != -1 && lineIndex != m_lastLineIndex)
{
m_lastLineIndex = lineIndex;
// Get the information about the selected word.
TMP_LineInfo lineInfo = m_TextComponent.textInfo.lineInfo[lineIndex];
// Send the event to any listeners.
char[] buffer = new char[lineInfo.characterCount];
for (int i = 0; i < lineInfo.characterCount && i < m_TextComponent.textInfo.characterInfo.Length; i++)
{
buffer[i] = m_TextComponent.textInfo.characterInfo[i + lineInfo.firstCharacterIndex].character;
}
string lineText = new string(buffer);
SendOnLineSelection(lineText, lineInfo.firstCharacterIndex, lineInfo.characterCount);
}
#endregion
#region Example of Link Handling
// Check if mouse intersects with any links.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextComponent, Input.mousePosition, m_Camera);
// Handle new Link selection.
if (linkIndex != -1 && linkIndex != m_selectedLink)
{
m_selectedLink = linkIndex;
// Get information about the link.
TMP_LinkInfo linkInfo = m_TextComponent.textInfo.linkInfo[linkIndex];
// Send the event to any listeners.
SendOnLinkSelection(linkInfo.GetLinkID(), linkInfo.GetLinkText(), linkIndex);
}
#endregion
}
else
{
// Reset all selections given we are hovering outside the text container bounds.
m_selectedLink = -1;
m_lastCharIndex = -1;
m_lastWordIndex = -1;
m_lastLineIndex = -1;
}
}
public void OnPointerEnter(PointerEventData eventData)
{
//Debug.Log("OnPointerEnter()");
}
public void OnPointerExit(PointerEventData eventData)
{
//Debug.Log("OnPointerExit()");
}
private void SendOnCharacterSelection(char character, int characterIndex)
{
if (onCharacterSelection != null)
onCharacterSelection.Invoke(character, characterIndex);
}
private void SendOnSpriteSelection(char character, int characterIndex)
{
if (onSpriteSelection != null)
onSpriteSelection.Invoke(character, characterIndex);
}
private void SendOnWordSelection(string word, int charIndex, int length)
{
if (onWordSelection != null)
onWordSelection.Invoke(word, charIndex, length);
}
private void SendOnLineSelection(string line, int charIndex, int length)
{
if (onLineSelection != null)
onLineSelection.Invoke(line, charIndex, length);
}
private void SendOnLinkSelection(string linkID, string linkText, int linkIndex)
{
if (onLinkSelection != null)
onLinkSelection.Invoke(linkID, linkText, linkIndex);
}
}
}
fileFormatVersion: 2
guid: 1312ae25639a4bae8e25ae223209cc50
timeCreated: 1452811039
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace TMPro.Examples
{
public class TMP_TextInfoDebugTool : MonoBehaviour
{
// Since this script is used for debugging, we exclude it from builds.
// TODO: Rework this script to make it into an editor utility.
#if UNITY_EDITOR
public bool ShowCharacters;
public bool ShowWords;
public bool ShowLinks;
public bool ShowLines;
public bool ShowMeshBounds;
public bool ShowTextBounds;
[Space(10)]
[TextArea(2, 2)]
public string ObjectStats;
[SerializeField]
private TMP_Text m_TextComponent;
private Transform m_Transform;
private TMP_TextInfo m_TextInfo;
private float m_ScaleMultiplier;
private float m_HandleSize;
void OnDrawGizmos()
{
if (m_TextComponent == null)
{
m_TextComponent = GetComponent<TMP_Text>();
if (m_TextComponent == null)
return;
}
m_Transform = m_TextComponent.transform;
// Get a reference to the text object's textInfo
m_TextInfo = m_TextComponent.textInfo;
// Update Text Statistics
ObjectStats = "Characters: " + m_TextInfo.characterCount + " Words: " + m_TextInfo.wordCount + " Spaces: " + m_TextInfo.spaceCount + " Sprites: " + m_TextInfo.spriteCount + " Links: " + m_TextInfo.linkCount
+ "\nLines: " + m_TextInfo.lineCount + " Pages: " + m_TextInfo.pageCount;
// Get the handle size for drawing the various
m_ScaleMultiplier = m_TextComponent.GetType() == typeof(TextMeshPro) ? 1 : 0.1f;
m_HandleSize = HandleUtility.GetHandleSize(m_Transform.position) * m_ScaleMultiplier;
// Draw line metrics
#region Draw Lines
if (ShowLines)
DrawLineBounds();
#endregion
// Draw word metrics
#region Draw Words
if (ShowWords)
DrawWordBounds();
#endregion
// Draw character metrics
#region Draw Characters
if (ShowCharacters)
DrawCharactersBounds();
#endregion
// Draw Quads around each of the words
#region Draw Links
if (ShowLinks)
DrawLinkBounds();
#endregion
// Draw Quad around the bounds of the text
#region Draw Bounds
if (ShowMeshBounds)
DrawBounds();
#endregion
// Draw Quad around the rendered region of the text.
#region Draw Text Bounds
if (ShowTextBounds)
DrawTextBounds();
#endregion
}
/// <summary>
/// Method to draw a rectangle around each character.
/// </summary>
/// <param name="text"></param>
void DrawCharactersBounds()
{
int characterCount = m_TextInfo.characterCount;
for (int i = 0; i < characterCount; i++)
{
// Draw visible as well as invisible characters
TMP_CharacterInfo characterInfo = m_TextInfo.characterInfo[i];
bool isCharacterVisible = i < m_TextComponent.maxVisibleCharacters &&
characterInfo.lineNumber < m_TextComponent.maxVisibleLines &&
i >= m_TextComponent.firstVisibleCharacter;
if (m_TextComponent.overflowMode == TextOverflowModes.Page)
isCharacterVisible = isCharacterVisible && characterInfo.pageNumber + 1 == m_TextComponent.pageToDisplay;
if (!isCharacterVisible)
continue;
float dottedLineSize = 6;
// Get Bottom Left and Top Right position of the current character
Vector3 bottomLeft = m_Transform.TransformPoint(characterInfo.bottomLeft);
Vector3 topLeft = m_Transform.TransformPoint(new Vector3(characterInfo.topLeft.x, characterInfo.topLeft.y, 0));
Vector3 topRight = m_Transform.TransformPoint(characterInfo.topRight);
Vector3 bottomRight = m_Transform.TransformPoint(new Vector3(characterInfo.bottomRight.x, characterInfo.bottomRight.y, 0));
// Draw character bounds
if (characterInfo.isVisible)
{
Color color = Color.green;
DrawDottedRectangle(bottomLeft, topRight, color);
}
else
{
Color color = Color.grey;
float whiteSpaceAdvance = Math.Abs(characterInfo.origin - characterInfo.xAdvance) > 0.01f ? characterInfo.xAdvance : characterInfo.origin + (characterInfo.ascender - characterInfo.descender) * 0.03f;
DrawDottedRectangle(m_Transform.TransformPoint(new Vector3(characterInfo.origin, characterInfo.descender, 0)), m_Transform.TransformPoint(new Vector3(whiteSpaceAdvance, characterInfo.ascender, 0)), color, 4);
}
float origin = characterInfo.origin;
float advance = characterInfo.xAdvance;
float ascentline = characterInfo.ascender;
float baseline = characterInfo.baseLine;
float descentline = characterInfo.descender;
//Draw Ascent line
Vector3 ascentlineStart = m_Transform.TransformPoint(new Vector3(origin, ascentline, 0));
Vector3 ascentlineEnd = m_Transform.TransformPoint(new Vector3(advance, ascentline, 0));
Handles.color = Color.cyan;
Handles.DrawDottedLine(ascentlineStart, ascentlineEnd, dottedLineSize);
// Draw Cap Height & Mean line
float capline = characterInfo.fontAsset == null ? 0 : baseline + characterInfo.fontAsset.faceInfo.capLine * characterInfo.scale;
Vector3 capHeightStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, capline, 0)).y, 0);
Vector3 capHeightEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, capline, 0)).y, 0);
float meanline = characterInfo.fontAsset == null ? 0 : baseline + characterInfo.fontAsset.faceInfo.meanLine * characterInfo.scale;
Vector3 meanlineStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, meanline, 0)).y, 0);
Vector3 meanlineEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, meanline, 0)).y, 0);
if (characterInfo.isVisible)
{
// Cap line
Handles.color = Color.cyan;
Handles.DrawDottedLine(capHeightStart, capHeightEnd, dottedLineSize);
// Mean line
Handles.color = Color.cyan;
Handles.DrawDottedLine(meanlineStart, meanlineEnd, dottedLineSize);
}
//Draw Base line
Vector3 baselineStart = m_Transform.TransformPoint(new Vector3(origin, baseline, 0));
Vector3 baselineEnd = m_Transform.TransformPoint(new Vector3(advance, baseline, 0));
Handles.color = Color.cyan;
Handles.DrawDottedLine(baselineStart, baselineEnd, dottedLineSize);
//Draw Descent line
Vector3 descentlineStart = m_Transform.TransformPoint(new Vector3(origin, descentline, 0));
Vector3 descentlineEnd = m_Transform.TransformPoint(new Vector3(advance, descentline, 0));
Handles.color = Color.cyan;
Handles.DrawDottedLine(descentlineStart, descentlineEnd, dottedLineSize);
// Draw Origin
Vector3 originPosition = m_Transform.TransformPoint(new Vector3(origin, baseline, 0));
DrawCrosshair(originPosition, 0.05f / m_ScaleMultiplier, Color.cyan);
// Draw Horizontal Advance
Vector3 advancePosition = m_Transform.TransformPoint(new Vector3(advance, baseline, 0));
DrawSquare(advancePosition, 0.025f / m_ScaleMultiplier, Color.yellow);
DrawCrosshair(advancePosition, 0.0125f / m_ScaleMultiplier, Color.yellow);
// Draw text labels for metrics
if (m_HandleSize < 0.5f)
{
GUIStyle style = new GUIStyle(GUI.skin.GetStyle("Label"));
style.normal.textColor = new Color(0.6f, 0.6f, 0.6f, 1.0f);
style.fontSize = 12;
style.fixedWidth = 200;
style.fixedHeight = 20;
Vector3 labelPosition;
float center = (origin + advance) / 2;
//float baselineMetrics = 0;
//float ascentlineMetrics = ascentline - baseline;
//float caplineMetrics = capline - baseline;
//float meanlineMetrics = meanline - baseline;
//float descentlineMetrics = descentline - baseline;
// Ascent Line
labelPosition = m_Transform.TransformPoint(new Vector3(center, ascentline, 0));
style.alignment = TextAnchor.UpperCenter;
Handles.Label(labelPosition, "Ascent Line", style);
//Handles.Label(labelPosition, "Ascent Line (" + ascentlineMetrics.ToString("f3") + ")" , style);
// Base Line
labelPosition = m_Transform.TransformPoint(new Vector3(center, baseline, 0));
Handles.Label(labelPosition, "Base Line", style);
//Handles.Label(labelPosition, "Base Line (" + baselineMetrics.ToString("f3") + ")" , style);
// Descent line
labelPosition = m_Transform.TransformPoint(new Vector3(center, descentline, 0));
Handles.Label(labelPosition, "Descent Line", style);
//Handles.Label(labelPosition, "Descent Line (" + descentlineMetrics.ToString("f3") + ")" , style);
if (characterInfo.isVisible)
{
// Cap Line
labelPosition = m_Transform.TransformPoint(new Vector3(center, capline, 0));
style.alignment = TextAnchor.UpperCenter;
Handles.Label(labelPosition, "Cap Line", style);
//Handles.Label(labelPosition, "Cap Line (" + caplineMetrics.ToString("f3") + ")" , style);
// Mean Line
labelPosition = m_Transform.TransformPoint(new Vector3(center, meanline, 0));
style.alignment = TextAnchor.UpperCenter;
Handles.Label(labelPosition, "Mean Line", style);
//Handles.Label(labelPosition, "Mean Line (" + ascentlineMetrics.ToString("f3") + ")" , style);
// Origin
labelPosition = m_Transform.TransformPoint(new Vector3(origin, baseline, 0));
style.alignment = TextAnchor.UpperRight;
Handles.Label(labelPosition, "Origin ", style);
// Advance
labelPosition = m_Transform.TransformPoint(new Vector3(advance, baseline, 0));
style.alignment = TextAnchor.UpperLeft;
Handles.Label(labelPosition, " Advance", style);
}
}
}
}
/// <summary>
/// Method to draw rectangles around each word of the text.
/// </summary>
/// <param name="text"></param>
void DrawWordBounds()
{
for (int i = 0; i < m_TextInfo.wordCount; i++)
{
TMP_WordInfo wInfo = m_TextInfo.wordInfo[i];
bool isBeginRegion = false;
Vector3 bottomLeft = Vector3.zero;
Vector3 topLeft = Vector3.zero;
Vector3 bottomRight = Vector3.zero;
Vector3 topRight = Vector3.zero;
float maxAscender = -Mathf.Infinity;
float minDescender = Mathf.Infinity;
Color wordColor = Color.green;
// Iterate through each character of the word
for (int j = 0; j < wInfo.characterCount; j++)
{
int characterIndex = wInfo.firstCharacterIndex + j;
TMP_CharacterInfo currentCharInfo = m_TextInfo.characterInfo[characterIndex];
int currentLine = currentCharInfo.lineNumber;
bool isCharacterVisible = characterIndex > m_TextComponent.maxVisibleCharacters ||
currentCharInfo.lineNumber > m_TextComponent.maxVisibleLines ||
(m_TextComponent.overflowMode == TextOverflowModes.Page && currentCharInfo.pageNumber + 1 != m_TextComponent.pageToDisplay) ? false : true;
// Track Max Ascender and Min Descender
maxAscender = Mathf.Max(maxAscender, currentCharInfo.ascender);
minDescender = Mathf.Min(minDescender, currentCharInfo.descender);
if (isBeginRegion == false && isCharacterVisible)
{
isBeginRegion = true;
bottomLeft = new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.descender, 0);
topLeft = new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.ascender, 0);
//Debug.Log("Start Word Region at [" + currentCharInfo.character + "]");
// If Word is one character
if (wInfo.characterCount == 1)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, wordColor);
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
}
}
// Last Character of Word
if (isBeginRegion && j == wInfo.characterCount - 1)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, wordColor);
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
}
// If Word is split on more than one line.
else if (isBeginRegion && currentLine != m_TextInfo.characterInfo[characterIndex + 1].lineNumber)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, wordColor);
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
maxAscender = -Mathf.Infinity;
minDescender = Mathf.Infinity;
}
}
//Debug.Log(wInfo.GetWord(m_TextMeshPro.textInfo.characterInfo));
}
}
/// <summary>
/// Draw rectangle around each of the links contained in the text.
/// </summary>
/// <param name="text"></param>
void DrawLinkBounds()
{
TMP_TextInfo textInfo = m_TextComponent.textInfo;
for (int i = 0; i < textInfo.linkCount; i++)
{
TMP_LinkInfo linkInfo = textInfo.linkInfo[i];
bool isBeginRegion = false;
Vector3 bottomLeft = Vector3.zero;
Vector3 topLeft = Vector3.zero;
Vector3 bottomRight = Vector3.zero;
Vector3 topRight = Vector3.zero;
float maxAscender = -Mathf.Infinity;
float minDescender = Mathf.Infinity;
Color32 linkColor = Color.cyan;
// Iterate through each character of the link text
for (int j = 0; j < linkInfo.linkTextLength; j++)
{
int characterIndex = linkInfo.linkTextfirstCharacterIndex + j;
TMP_CharacterInfo currentCharInfo = textInfo.characterInfo[characterIndex];
int currentLine = currentCharInfo.lineNumber;
bool isCharacterVisible = characterIndex > m_TextComponent.maxVisibleCharacters ||
currentCharInfo.lineNumber > m_TextComponent.maxVisibleLines ||
(m_TextComponent.overflowMode == TextOverflowModes.Page && currentCharInfo.pageNumber + 1 != m_TextComponent.pageToDisplay) ? false : true;
// Track Max Ascender and Min Descender
maxAscender = Mathf.Max(maxAscender, currentCharInfo.ascender);
minDescender = Mathf.Min(minDescender, currentCharInfo.descender);
if (isBeginRegion == false && isCharacterVisible)
{
isBeginRegion = true;
bottomLeft = new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.descender, 0);
topLeft = new Vector3(currentCharInfo.bottomLeft.x, currentCharInfo.ascender, 0);
//Debug.Log("Start Word Region at [" + currentCharInfo.character + "]");
// If Link is one character
if (linkInfo.linkTextLength == 1)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, linkColor);
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
}
}
// Last Character of Link
if (isBeginRegion && j == linkInfo.linkTextLength - 1)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, linkColor);
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
}
// If Link is split on more than one line.
else if (isBeginRegion && currentLine != textInfo.characterInfo[characterIndex + 1].lineNumber)
{
isBeginRegion = false;
topLeft = m_Transform.TransformPoint(new Vector3(topLeft.x, maxAscender, 0));
bottomLeft = m_Transform.TransformPoint(new Vector3(bottomLeft.x, minDescender, 0));
bottomRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, minDescender, 0));
topRight = m_Transform.TransformPoint(new Vector3(currentCharInfo.topRight.x, maxAscender, 0));
// Draw Region
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, linkColor);
maxAscender = -Mathf.Infinity;
minDescender = Mathf.Infinity;
//Debug.Log("End Word Region at [" + currentCharInfo.character + "]");
}
}
//Debug.Log(wInfo.GetWord(m_TextMeshPro.textInfo.characterInfo));
}
}
/// <summary>
/// Draw Rectangles around each lines of the text.
/// </summary>
/// <param name="text"></param>
void DrawLineBounds()
{
int lineCount = m_TextInfo.lineCount;
for (int i = 0; i < lineCount; i++)
{
TMP_LineInfo lineInfo = m_TextInfo.lineInfo[i];
TMP_CharacterInfo firstCharacterInfo = m_TextInfo.characterInfo[lineInfo.firstCharacterIndex];
TMP_CharacterInfo lastCharacterInfo = m_TextInfo.characterInfo[lineInfo.lastCharacterIndex];
bool isLineVisible = (lineInfo.characterCount == 1 && (firstCharacterInfo.character == 10 || firstCharacterInfo.character == 11 || firstCharacterInfo.character == 0x2028 || firstCharacterInfo.character == 0x2029)) ||
i > m_TextComponent.maxVisibleLines ||
(m_TextComponent.overflowMode == TextOverflowModes.Page && firstCharacterInfo.pageNumber + 1 != m_TextComponent.pageToDisplay) ? false : true;
if (!isLineVisible) continue;
float lineBottomLeft = firstCharacterInfo.bottomLeft.x;
float lineTopRight = lastCharacterInfo.topRight.x;
float ascentline = lineInfo.ascender;
float baseline = lineInfo.baseline;
float descentline = lineInfo.descender;
float dottedLineSize = 12;
// Draw line extents
DrawDottedRectangle(m_Transform.TransformPoint(lineInfo.lineExtents.min), m_Transform.TransformPoint(lineInfo.lineExtents.max), Color.green, 4);
// Draw Ascent line
Vector3 ascentlineStart = m_Transform.TransformPoint(new Vector3(lineBottomLeft, ascentline, 0));
Vector3 ascentlineEnd = m_Transform.TransformPoint(new Vector3(lineTopRight, ascentline, 0));
Handles.color = Color.yellow;
Handles.DrawDottedLine(ascentlineStart, ascentlineEnd, dottedLineSize);
// Draw Base line
Vector3 baseLineStart = m_Transform.TransformPoint(new Vector3(lineBottomLeft, baseline, 0));
Vector3 baseLineEnd = m_Transform.TransformPoint(new Vector3(lineTopRight, baseline, 0));
Handles.color = Color.yellow;
Handles.DrawDottedLine(baseLineStart, baseLineEnd, dottedLineSize);
// Draw Descent line
Vector3 descentLineStart = m_Transform.TransformPoint(new Vector3(lineBottomLeft, descentline, 0));
Vector3 descentLineEnd = m_Transform.TransformPoint(new Vector3(lineTopRight, descentline, 0));
Handles.color = Color.yellow;
Handles.DrawDottedLine(descentLineStart, descentLineEnd, dottedLineSize);
// Draw text labels for metrics
if (m_HandleSize < 1.0f)
{
GUIStyle style = new GUIStyle();
style.normal.textColor = new Color(0.8f, 0.8f, 0.8f, 1.0f);
style.fontSize = 12;
style.fixedWidth = 200;
style.fixedHeight = 20;
Vector3 labelPosition;
// Ascent Line
labelPosition = m_Transform.TransformPoint(new Vector3(lineBottomLeft, ascentline, 0));
style.padding = new RectOffset(0, 10, 0, 5);
style.alignment = TextAnchor.MiddleRight;
Handles.Label(labelPosition, "Ascent Line", style);
// Base Line
labelPosition = m_Transform.TransformPoint(new Vector3(lineBottomLeft, baseline, 0));
Handles.Label(labelPosition, "Base Line", style);
// Descent line
labelPosition = m_Transform.TransformPoint(new Vector3(lineBottomLeft, descentline, 0));
Handles.Label(labelPosition, "Descent Line", style);
}
}
}
/// <summary>
/// Draw Rectangle around the bounds of the text object.
/// </summary>
void DrawBounds()
{
Bounds meshBounds = m_TextComponent.bounds;
// Get Bottom Left and Top Right position of each word
Vector3 bottomLeft = m_TextComponent.transform.position + meshBounds.min;
Vector3 topRight = m_TextComponent.transform.position + meshBounds.max;
DrawRectangle(bottomLeft, topRight, new Color(1, 0.5f, 0));
}
void DrawTextBounds()
{
Bounds textBounds = m_TextComponent.textBounds;
Vector3 bottomLeft = m_TextComponent.transform.position + (textBounds.center - textBounds.extents);
Vector3 topRight = m_TextComponent.transform.position + (textBounds.center + textBounds.extents);
DrawRectangle(bottomLeft, topRight, new Color(0f, 0.5f, 0.5f));
}
// Draw Rectangles
void DrawRectangle(Vector3 BL, Vector3 TR, Color color)
{
Gizmos.color = color;
Gizmos.DrawLine(new Vector3(BL.x, BL.y, 0), new Vector3(BL.x, TR.y, 0));
Gizmos.DrawLine(new Vector3(BL.x, TR.y, 0), new Vector3(TR.x, TR.y, 0));
Gizmos.DrawLine(new Vector3(TR.x, TR.y, 0), new Vector3(TR.x, BL.y, 0));
Gizmos.DrawLine(new Vector3(TR.x, BL.y, 0), new Vector3(BL.x, BL.y, 0));
}
void DrawDottedRectangle(Vector3 bottomLeft, Vector3 topRight, Color color, float size = 5.0f)
{
Handles.color = color;
Handles.DrawDottedLine(bottomLeft, new Vector3(bottomLeft.x, topRight.y, bottomLeft.z), size);
Handles.DrawDottedLine(new Vector3(bottomLeft.x, topRight.y, bottomLeft.z), topRight, size);
Handles.DrawDottedLine(topRight, new Vector3(topRight.x, bottomLeft.y, bottomLeft.z), size);
Handles.DrawDottedLine(new Vector3(topRight.x, bottomLeft.y, bottomLeft.z), bottomLeft, size);
}
void DrawSolidRectangle(Vector3 bottomLeft, Vector3 topRight, Color color, float size = 5.0f)
{
Handles.color = color;
Rect rect = new Rect(bottomLeft, topRight - bottomLeft);
Handles.DrawSolidRectangleWithOutline(rect, color, Color.black);
}
void DrawSquare(Vector3 position, float size, Color color)
{
Handles.color = color;
Vector3 bottomLeft = new Vector3(position.x - size, position.y - size, position.z);
Vector3 topLeft = new Vector3(position.x - size, position.y + size, position.z);
Vector3 topRight = new Vector3(position.x + size, position.y + size, position.z);
Vector3 bottomRight = new Vector3(position.x + size, position.y - size, position.z);
Handles.DrawLine(bottomLeft, topLeft);
Handles.DrawLine(topLeft, topRight);
Handles.DrawLine(topRight, bottomRight);
Handles.DrawLine(bottomRight, bottomLeft);
}
void DrawCrosshair(Vector3 position, float size, Color color)
{
Handles.color = color;
Handles.DrawLine(new Vector3(position.x - size, position.y, position.z), new Vector3(position.x + size, position.y, position.z));
Handles.DrawLine(new Vector3(position.x, position.y - size, position.z), new Vector3(position.x, position.y + size, position.z));
}
// Draw Rectangles
void DrawRectangle(Vector3 bl, Vector3 tl, Vector3 tr, Vector3 br, Color color)
{
Gizmos.color = color;
Gizmos.DrawLine(bl, tl);
Gizmos.DrawLine(tl, tr);
Gizmos.DrawLine(tr, br);
Gizmos.DrawLine(br, bl);
}
// Draw Rectangles
void DrawDottedRectangle(Vector3 bl, Vector3 tl, Vector3 tr, Vector3 br, Color color)
{
var cam = Camera.current;
float dotSpacing = (cam.WorldToScreenPoint(br).x - cam.WorldToScreenPoint(bl).x) / 75f;
UnityEditor.Handles.color = color;
UnityEditor.Handles.DrawDottedLine(bl, tl, dotSpacing);
UnityEditor.Handles.DrawDottedLine(tl, tr, dotSpacing);
UnityEditor.Handles.DrawDottedLine(tr, br, dotSpacing);
UnityEditor.Handles.DrawDottedLine(br, bl, dotSpacing);
}
#endif
}
}
fileFormatVersion: 2
guid: 21256c5b62f346f18640dad779911e20
timeCreated: 1430348781
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
namespace TMPro.Examples
{
public class TMP_TextSelector_A : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private TextMeshPro m_TextMeshPro;
private Camera m_Camera;
private bool m_isHoveringObject;
private int m_selectedLink = -1;
private int m_lastCharIndex = -1;
private int m_lastWordIndex = -1;
void Awake()
{
m_TextMeshPro = gameObject.GetComponent<TextMeshPro>();
m_Camera = Camera.main;
// Force generation of the text object so we have valid data to work with. This is needed since LateUpdate() will be called before the text object has a chance to generated when entering play mode.
m_TextMeshPro.ForceMeshUpdate();
}
void LateUpdate()
{
m_isHoveringObject = false;
if (TMP_TextUtilities.IsIntersectingRectTransform(m_TextMeshPro.rectTransform, Input.mousePosition, Camera.main))
{
m_isHoveringObject = true;
}
if (m_isHoveringObject)
{
#region Example of Character Selection
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, Camera.main, true);
if (charIndex != -1 && charIndex != m_lastCharIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
//Debug.Log("[" + m_TextMeshPro.textInfo.characterInfo[charIndex].character + "] has been selected.");
m_lastCharIndex = charIndex;
int meshIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].materialReferenceIndex;
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
//m_TextMeshPro.mesh.colors32 = vertexColors;
m_TextMeshPro.textInfo.meshInfo[meshIndex].mesh.colors32 = vertexColors;
}
#endregion
#region Example of Link Handling
// Check if mouse intersects with any links.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous link selection if one existed.
if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
{
//m_TextPopup_RectTransform.gameObject.SetActive(false);
m_selectedLink = -1;
}
// Handle new Link selection.
if (linkIndex != -1 && linkIndex != m_selectedLink)
{
m_selectedLink = linkIndex;
TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
// The following provides an example of how to access the link properties.
//Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\" Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.
Vector3 worldPointInRectangle;
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);
switch (linkInfo.GetLinkID())
{
case "id_01": // 100041637: // id_01
//m_TextPopup_RectTransform.position = worldPointInRectangle;
//m_TextPopup_RectTransform.gameObject.SetActive(true);
//m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
break;
case "id_02": // 100041638: // id_02
//m_TextPopup_RectTransform.position = worldPointInRectangle;
//m_TextPopup_RectTransform.gameObject.SetActive(true);
//m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
break;
}
}
#endregion
#region Example of Word Selection
// Check if Mouse intersects any words and if so assign a random color to that word.
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, Camera.main);
if (wordIndex != -1 && wordIndex != m_lastWordIndex)
{
m_lastWordIndex = wordIndex;
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];
Vector3 wordPOS = m_TextMeshPro.transform.TransformPoint(m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex].bottomLeft);
wordPOS = Camera.main.WorldToScreenPoint(wordPOS);
//Debug.Log("Mouse Position: " + Input.mousePosition.ToString("f3") + " Word Position: " + wordPOS.ToString("f3"));
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[0].colors32;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
for (int i = 0; i < wInfo.characterCount; i++)
{
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
}
m_TextMeshPro.mesh.colors32 = vertexColors;
}
#endregion
}
}
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("OnPointerEnter()");
m_isHoveringObject = true;
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("OnPointerExit()");
m_isHoveringObject = false;
}
}
}
fileFormatVersion: 2
guid: 103e0a6a1d404693b9fb1a5173e0e979
timeCreated: 1452811039
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
#pragma warning disable 0618 // Disabled warning due to SetVertices being deprecated until new release with SetMesh() is available.
namespace TMPro.Examples
{
public class TMP_TextSelector_B : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler, IPointerUpHandler
{
public RectTransform TextPopup_Prefab_01;
private RectTransform m_TextPopup_RectTransform;
private TextMeshProUGUI m_TextPopup_TMPComponent;
private const string k_LinkText = "You have selected link <#ffff00>";
private const string k_WordText = "Word Index: <#ffff00>";
private TextMeshProUGUI m_TextMeshPro;
private Canvas m_Canvas;
private Camera m_Camera;
// Flags
private bool isHoveringObject;
private int m_selectedWord = -1;
private int m_selectedLink = -1;
private int m_lastIndex = -1;
private Matrix4x4 m_matrix;
private TMP_MeshInfo[] m_cachedMeshInfoVertexData;
void Awake()
{
m_TextMeshPro = gameObject.GetComponent<TextMeshProUGUI>();
m_Canvas = gameObject.GetComponentInParent<Canvas>();
// Get a reference to the camera if Canvas Render Mode is not ScreenSpace Overlay.
if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
m_Camera = null;
else
m_Camera = m_Canvas.worldCamera;
// Create pop-up text object which is used to show the link information.
m_TextPopup_RectTransform = Instantiate(TextPopup_Prefab_01) as RectTransform;
m_TextPopup_RectTransform.SetParent(m_Canvas.transform, false);
m_TextPopup_TMPComponent = m_TextPopup_RectTransform.GetComponentInChildren<TextMeshProUGUI>();
m_TextPopup_RectTransform.gameObject.SetActive(false);
}
void OnEnable()
{
// Subscribe to event fired when text object has been regenerated.
TMPro_EventManager.TEXT_CHANGED_EVENT.Add(ON_TEXT_CHANGED);
}
void OnDisable()
{
// UnSubscribe to event fired when text object has been regenerated.
TMPro_EventManager.TEXT_CHANGED_EVENT.Remove(ON_TEXT_CHANGED);
}
void ON_TEXT_CHANGED(Object obj)
{
if (obj == m_TextMeshPro)
{
// Update cached vertex data.
m_cachedMeshInfoVertexData = m_TextMeshPro.textInfo.CopyMeshInfoVertexData();
}
}
void LateUpdate()
{
if (isHoveringObject)
{
// Check if Mouse Intersects any of the characters. If so, assign a random color.
#region Handle Character Selection
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);
// Undo Swap and Vertex Attribute changes.
if (charIndex == -1 || charIndex != m_lastIndex)
{
RestoreCachedVertexAttributes(m_lastIndex);
m_lastIndex = -1;
}
if (charIndex != -1 && charIndex != m_lastIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
m_lastIndex = charIndex;
// Get the index of the material / sub text object used by this character.
int materialIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].materialReferenceIndex;
// Get the index of the first vertex of the selected character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;
// Get a reference to the vertices array.
Vector3[] vertices = m_TextMeshPro.textInfo.meshInfo[materialIndex].vertices;
// Determine the center point of the character.
Vector2 charMidBasline = (vertices[vertexIndex + 0] + vertices[vertexIndex + 2]) / 2;
// Need to translate all 4 vertices of the character to aligned with middle of character / baseline.
// This is needed so the matrix TRS is applied at the origin for each character.
Vector3 offset = charMidBasline;
// Translate the character to the middle baseline.
vertices[vertexIndex + 0] = vertices[vertexIndex + 0] - offset;
vertices[vertexIndex + 1] = vertices[vertexIndex + 1] - offset;
vertices[vertexIndex + 2] = vertices[vertexIndex + 2] - offset;
vertices[vertexIndex + 3] = vertices[vertexIndex + 3] - offset;
float zoomFactor = 1.5f;
// Setup the Matrix for the scale change.
m_matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one * zoomFactor);
// Apply Matrix operation on the given character.
vertices[vertexIndex + 0] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 0]);
vertices[vertexIndex + 1] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]);
vertices[vertexIndex + 2] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]);
vertices[vertexIndex + 3] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]);
// Translate the character back to its original position.
vertices[vertexIndex + 0] = vertices[vertexIndex + 0] + offset;
vertices[vertexIndex + 1] = vertices[vertexIndex + 1] + offset;
vertices[vertexIndex + 2] = vertices[vertexIndex + 2] + offset;
vertices[vertexIndex + 3] = vertices[vertexIndex + 3] + offset;
// Change Vertex Colors of the highlighted character
Color32 c = new Color32(255, 255, 192, 255);
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
// Get a reference to the meshInfo of the selected character.
TMP_MeshInfo meshInfo = m_TextMeshPro.textInfo.meshInfo[materialIndex];
// Get the index of the last character's vertex attributes.
int lastVertexIndex = vertices.Length - 4;
// Swap the current character's vertex attributes with those of the last element in the vertex attribute arrays.
// We do this to make sure this character is rendered last and over other characters.
meshInfo.SwapVertexData(vertexIndex, lastVertexIndex);
// Need to update the appropriate
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
#endregion
#region Word Selection Handling
//Check if Mouse intersects any words and if so assign a random color to that word.
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous word selection.
if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
{
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int characterIndex = wInfo.firstCharacterIndex + i;
// Get the index of the material / sub text object used by this character.
int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;
// Get the index of the first vertex of this character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;
Color32 c = vertexColors[vertexIndex + 0].Tint(1.33333f);
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
}
// Update Geometry
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
m_selectedWord = -1;
}
// Word Selection Handling
if (wordIndex != -1 && wordIndex != m_selectedWord && !(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
m_selectedWord = wordIndex;
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int characterIndex = wInfo.firstCharacterIndex + i;
// Get the index of the material / sub text object used by this character.
int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;
Color32 c = vertexColors[vertexIndex + 0].Tint(0.75f);
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
}
// Update Geometry
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
#endregion
#region Example of Link Handling
// Check if mouse intersects with any links.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous link selection if one existed.
if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
{
m_TextPopup_RectTransform.gameObject.SetActive(false);
m_selectedLink = -1;
}
// Handle new Link selection.
if (linkIndex != -1 && linkIndex != m_selectedLink)
{
m_selectedLink = linkIndex;
TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
// Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\" Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.
Vector3 worldPointInRectangle;
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);
switch (linkInfo.GetLinkID())
{
case "id_01": // 100041637: // id_01
m_TextPopup_RectTransform.position = worldPointInRectangle;
m_TextPopup_RectTransform.gameObject.SetActive(true);
m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
break;
case "id_02": // 100041638: // id_02
m_TextPopup_RectTransform.position = worldPointInRectangle;
m_TextPopup_RectTransform.gameObject.SetActive(true);
m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
break;
}
}
#endregion
}
else
{
// Restore any character that may have been modified
if (m_lastIndex != -1)
{
RestoreCachedVertexAttributes(m_lastIndex);
m_lastIndex = -1;
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
//Debug.Log("OnPointerEnter()");
isHoveringObject = true;
}
public void OnPointerExit(PointerEventData eventData)
{
//Debug.Log("OnPointerExit()");
isHoveringObject = false;
}
public void OnPointerClick(PointerEventData eventData)
{
//Debug.Log("Click at POS: " + eventData.position + " World POS: " + eventData.worldPosition);
// Check if Mouse Intersects any of the characters. If so, assign a random color.
#region Character Selection Handling
/*
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);
if (charIndex != -1 && charIndex != m_lastIndex)
{
//Debug.Log("Character [" + m_TextMeshPro.textInfo.characterInfo[index].character + "] was selected at POS: " + eventData.position);
m_lastIndex = charIndex;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
}
*/
#endregion
#region Word Selection Handling
//Check if Mouse intersects any words and if so assign a random color to that word.
/*
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous word selection.
if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
{
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];
// Get a reference to the uiVertices array.
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;
Color32 c = uiVertices[vertexIndex + 0].color.Tint(1.33333f);
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
m_selectedWord = -1;
}
// Handle word selection
if (wordIndex != -1 && wordIndex != m_selectedWord)
{
m_selectedWord = wordIndex;
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];
// Get a reference to the uiVertices array.
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;
Color32 c = uiVertices[vertexIndex + 0].color.Tint(0.75f);
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
}
*/
#endregion
#region Link Selection Handling
/*
// Check if Mouse intersects any words and if so assign a random color to that word.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);
if (linkIndex != -1)
{
TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
int linkHashCode = linkInfo.hashCode;
//Debug.Log(TMP_TextUtilities.GetSimpleHashCode("id_02"));
switch (linkHashCode)
{
case 291445: // id_01
if (m_LinkObject01 == null)
m_LinkObject01 = Instantiate(Link_01_Prefab);
else
{
m_LinkObject01.gameObject.SetActive(true);
}
break;
case 291446: // id_02
break;
}
// Example of how to modify vertex attributes like colors
#region Vertex Attribute Modification Example
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
for (int i = 0; i < linkInfo.characterCount; i++)
{
TMP_CharacterInfo cInfo = m_TextMeshPro.textInfo.characterInfo[linkInfo.firstCharacterIndex + i];
if (!cInfo.isVisible) continue; // Skip invisible characters.
int vertexIndex = cInfo.vertexIndex;
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
#endregion
}
*/
#endregion
}
public void OnPointerUp(PointerEventData eventData)
{
//Debug.Log("OnPointerUp()");
}
void RestoreCachedVertexAttributes(int index)
{
if (index == -1 || index > m_TextMeshPro.textInfo.characterCount - 1) return;
// Get the index of the material / sub text object used by this character.
int materialIndex = m_TextMeshPro.textInfo.characterInfo[index].materialReferenceIndex;
// Get the index of the first vertex of the selected character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[index].vertexIndex;
// Restore Vertices
// Get a reference to the cached / original vertices.
Vector3[] src_vertices = m_cachedMeshInfoVertexData[materialIndex].vertices;
// Get a reference to the vertices that we need to replace.
Vector3[] dst_vertices = m_TextMeshPro.textInfo.meshInfo[materialIndex].vertices;
// Restore / Copy vertices from source to destination
dst_vertices[vertexIndex + 0] = src_vertices[vertexIndex + 0];
dst_vertices[vertexIndex + 1] = src_vertices[vertexIndex + 1];
dst_vertices[vertexIndex + 2] = src_vertices[vertexIndex + 2];
dst_vertices[vertexIndex + 3] = src_vertices[vertexIndex + 3];
// Restore Vertex Colors
// Get a reference to the vertex colors we need to replace.
Color32[] dst_colors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
// Get a reference to the cached / original vertex colors.
Color32[] src_colors = m_cachedMeshInfoVertexData[materialIndex].colors32;
// Copy the vertex colors from source to destination.
dst_colors[vertexIndex + 0] = src_colors[vertexIndex + 0];
dst_colors[vertexIndex + 1] = src_colors[vertexIndex + 1];
dst_colors[vertexIndex + 2] = src_colors[vertexIndex + 2];
dst_colors[vertexIndex + 3] = src_colors[vertexIndex + 3];
// Restore UV0S
// UVS0
Vector2[] src_uv0s = m_cachedMeshInfoVertexData[materialIndex].uvs0;
Vector2[] dst_uv0s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs0;
dst_uv0s[vertexIndex + 0] = src_uv0s[vertexIndex + 0];
dst_uv0s[vertexIndex + 1] = src_uv0s[vertexIndex + 1];
dst_uv0s[vertexIndex + 2] = src_uv0s[vertexIndex + 2];
dst_uv0s[vertexIndex + 3] = src_uv0s[vertexIndex + 3];
// UVS2
Vector2[] src_uv2s = m_cachedMeshInfoVertexData[materialIndex].uvs2;
Vector2[] dst_uv2s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs2;
dst_uv2s[vertexIndex + 0] = src_uv2s[vertexIndex + 0];
dst_uv2s[vertexIndex + 1] = src_uv2s[vertexIndex + 1];
dst_uv2s[vertexIndex + 2] = src_uv2s[vertexIndex + 2];
dst_uv2s[vertexIndex + 3] = src_uv2s[vertexIndex + 3];
// Restore last vertex attribute as we swapped it as well
int lastIndex = (src_vertices.Length / 4 - 1) * 4;
// Vertices
dst_vertices[lastIndex + 0] = src_vertices[lastIndex + 0];
dst_vertices[lastIndex + 1] = src_vertices[lastIndex + 1];
dst_vertices[lastIndex + 2] = src_vertices[lastIndex + 2];
dst_vertices[lastIndex + 3] = src_vertices[lastIndex + 3];
// Vertex Colors
src_colors = m_cachedMeshInfoVertexData[materialIndex].colors32;
dst_colors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
dst_colors[lastIndex + 0] = src_colors[lastIndex + 0];
dst_colors[lastIndex + 1] = src_colors[lastIndex + 1];
dst_colors[lastIndex + 2] = src_colors[lastIndex + 2];
dst_colors[lastIndex + 3] = src_colors[lastIndex + 3];
// UVS0
src_uv0s = m_cachedMeshInfoVertexData[materialIndex].uvs0;
dst_uv0s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs0;
dst_uv0s[lastIndex + 0] = src_uv0s[lastIndex + 0];
dst_uv0s[lastIndex + 1] = src_uv0s[lastIndex + 1];
dst_uv0s[lastIndex + 2] = src_uv0s[lastIndex + 2];
dst_uv0s[lastIndex + 3] = src_uv0s[lastIndex + 3];
// UVS2
src_uv2s = m_cachedMeshInfoVertexData[materialIndex].uvs2;
dst_uv2s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs2;
dst_uv2s[lastIndex + 0] = src_uv2s[lastIndex + 0];
dst_uv2s[lastIndex + 1] = src_uv2s[lastIndex + 1];
dst_uv2s[lastIndex + 2] = src_uv2s[lastIndex + 2];
dst_uv2s[lastIndex + 3] = src_uv2s[lastIndex + 3];
// Need to update the appropriate
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
}
}
fileFormatVersion: 2
guid: a05dcd8be7ec4ccbb35c26219884aa37
timeCreated: 1435531209
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences:
- TextPopup_Prefab_01: {fileID: 22450954, guid: b06f0e6c1dfa4356ac918da1bb32c603,
type: 2}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TMP_UiFrameRateCounter : MonoBehaviour
{
public float UpdateInterval = 5.0f;
private float m_LastInterval = 0;
private int m_Frames = 0;
public enum FpsCounterAnchorPositions { TopLeft, BottomLeft, TopRight, BottomRight };
public FpsCounterAnchorPositions AnchorPosition = FpsCounterAnchorPositions.TopRight;
private string htmlColorTag;
private const string fpsLabel = "{0:2}</color> <#8080ff>FPS \n<#FF8000>{1:2} <#8080ff>MS";
private TextMeshProUGUI m_TextMeshPro;
private RectTransform m_frameCounter_transform;
private FpsCounterAnchorPositions last_AnchorPosition;
void Awake()
{
if (!enabled)
return;
Application.targetFrameRate = 1000;
GameObject frameCounter = new GameObject("Frame Counter");
m_frameCounter_transform = frameCounter.AddComponent<RectTransform>();
m_frameCounter_transform.SetParent(this.transform, false);
m_TextMeshPro = frameCounter.AddComponent<TextMeshProUGUI>();
m_TextMeshPro.font = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
m_TextMeshPro.fontSharedMaterial = Resources.Load<Material>("Fonts & Materials/LiberationSans SDF - Overlay");
m_TextMeshPro.enableWordWrapping = false;
m_TextMeshPro.fontSize = 36;
m_TextMeshPro.isOverlay = true;
Set_FrameCounter_Position(AnchorPosition);
last_AnchorPosition = AnchorPosition;
}
void Start()
{
m_LastInterval = Time.realtimeSinceStartup;
m_Frames = 0;
}
void Update()
{
if (AnchorPosition != last_AnchorPosition)
Set_FrameCounter_Position(AnchorPosition);
last_AnchorPosition = AnchorPosition;
m_Frames += 1;
float timeNow = Time.realtimeSinceStartup;
if (timeNow > m_LastInterval + UpdateInterval)
{
// display two fractional digits (f2 format)
float fps = m_Frames / (timeNow - m_LastInterval);
float ms = 1000.0f / Mathf.Max(fps, 0.00001f);
if (fps < 30)
htmlColorTag = "<color=yellow>";
else if (fps < 10)
htmlColorTag = "<color=red>";
else
htmlColorTag = "<color=green>";
m_TextMeshPro.SetText(htmlColorTag + fpsLabel, fps, ms);
m_Frames = 0;
m_LastInterval = timeNow;
}
}
void Set_FrameCounter_Position(FpsCounterAnchorPositions anchor_position)
{
switch (anchor_position)
{
case FpsCounterAnchorPositions.TopLeft:
m_TextMeshPro.alignment = TextAlignmentOptions.TopLeft;
m_frameCounter_transform.pivot = new Vector2(0, 1);
m_frameCounter_transform.anchorMin = new Vector2(0.01f, 0.99f);
m_frameCounter_transform.anchorMax = new Vector2(0.01f, 0.99f);
m_frameCounter_transform.anchoredPosition = new Vector2(0, 1);
break;
case FpsCounterAnchorPositions.BottomLeft:
m_TextMeshPro.alignment = TextAlignmentOptions.BottomLeft;
m_frameCounter_transform.pivot = new Vector2(0, 0);
m_frameCounter_transform.anchorMin = new Vector2(0.01f, 0.01f);
m_frameCounter_transform.anchorMax = new Vector2(0.01f, 0.01f);
m_frameCounter_transform.anchoredPosition = new Vector2(0, 0);
break;
case FpsCounterAnchorPositions.TopRight:
m_TextMeshPro.alignment = TextAlignmentOptions.TopRight;
m_frameCounter_transform.pivot = new Vector2(1, 1);
m_frameCounter_transform.anchorMin = new Vector2(0.99f, 0.99f);
m_frameCounter_transform.anchorMax = new Vector2(0.99f, 0.99f);
m_frameCounter_transform.anchoredPosition = new Vector2(1, 1);
break;
case FpsCounterAnchorPositions.BottomRight:
m_TextMeshPro.alignment = TextAlignmentOptions.BottomRight;
m_frameCounter_transform.pivot = new Vector2(1, 0);
m_frameCounter_transform.anchorMin = new Vector2(0.99f, 0.01f);
m_frameCounter_transform.anchorMax = new Vector2(0.99f, 0.01f);
m_frameCounter_transform.anchoredPosition = new Vector2(1, 0);
break;
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 24b0dc2d1d494adbbec1f4db26b4cf83
timeCreated: 1448607572
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TMPro_InstructionOverlay : MonoBehaviour
{
public enum FpsCounterAnchorPositions { TopLeft, BottomLeft, TopRight, BottomRight };
public FpsCounterAnchorPositions AnchorPosition = FpsCounterAnchorPositions.BottomLeft;
private const string instructions = "Camera Control - <#ffff00>Shift + RMB\n</color>Zoom - <#ffff00>Mouse wheel.";
private TextMeshPro m_TextMeshPro;
private TextContainer m_textContainer;
private Transform m_frameCounter_transform;
private Camera m_camera;
//private FpsCounterAnchorPositions last_AnchorPosition;
void Awake()
{
if (!enabled)
return;
m_camera = Camera.main;
GameObject frameCounter = new GameObject("Frame Counter");
m_frameCounter_transform = frameCounter.transform;
m_frameCounter_transform.parent = m_camera.transform;
m_frameCounter_transform.localRotation = Quaternion.identity;
m_TextMeshPro = frameCounter.AddComponent<TextMeshPro>();
m_TextMeshPro.font = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
m_TextMeshPro.fontSharedMaterial = Resources.Load<Material>("Fonts & Materials/LiberationSans SDF - Overlay");
m_TextMeshPro.fontSize = 30;
m_TextMeshPro.isOverlay = true;
m_textContainer = frameCounter.GetComponent<TextContainer>();
Set_FrameCounter_Position(AnchorPosition);
//last_AnchorPosition = AnchorPosition;
m_TextMeshPro.text = instructions;
}
void Set_FrameCounter_Position(FpsCounterAnchorPositions anchor_position)
{
switch (anchor_position)
{
case FpsCounterAnchorPositions.TopLeft:
//m_TextMeshPro.anchor = AnchorPositions.TopLeft;
m_textContainer.anchorPosition = TextContainerAnchors.TopLeft;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomLeft:
//m_TextMeshPro.anchor = AnchorPositions.BottomLeft;
m_textContainer.anchorPosition = TextContainerAnchors.BottomLeft;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 0, 100.0f));
break;
case FpsCounterAnchorPositions.TopRight:
//m_TextMeshPro.anchor = AnchorPositions.TopRight;
m_textContainer.anchorPosition = TextContainerAnchors.TopRight;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomRight:
//m_TextMeshPro.anchor = AnchorPositions.BottomRight;
m_textContainer.anchorPosition = TextContainerAnchors.BottomRight;
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 0, 100.0f));
break;
}
}
}
}
fileFormatVersion: 2
guid: c3c1afeda5e545e0b19add5373896d2e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TeleType : MonoBehaviour
{
//[Range(0, 100)]
//public int RevealSpeed = 50;
private string label01 = "Example <sprite=2> of using <sprite=7> <#ffa000>Graphics Inline</color> <sprite=5> with Text in <font=\"Bangers SDF\" material=\"Bangers SDF - Drop Shadow\">TextMesh<#40a0ff>Pro</color></font><sprite=0> and Unity<sprite=1>";
private string label02 = "Example <sprite=2> of using <sprite=7> <#ffa000>Graphics Inline</color> <sprite=5> with Text in <font=\"Bangers SDF\" material=\"Bangers SDF - Drop Shadow\">TextMesh<#40a0ff>Pro</color></font><sprite=0> and Unity<sprite=2>";
private TMP_Text m_textMeshPro;
void Awake()
{
// Get Reference to TextMeshPro Component
m_textMeshPro = GetComponent<TMP_Text>();
m_textMeshPro.text = label01;
m_textMeshPro.enableWordWrapping = true;
m_textMeshPro.alignment = TextAlignmentOptions.Top;
//if (GetComponentInParent(typeof(Canvas)) as Canvas == null)
//{
// GameObject canvas = new GameObject("Canvas", typeof(Canvas));
// gameObject.transform.SetParent(canvas.transform);
// canvas.GetComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
// // Set RectTransform Size
// gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(500, 300);
// m_textMeshPro.fontSize = 48;
//}
}
IEnumerator Start()
{
// Force and update of the mesh to get valid information.
m_textMeshPro.ForceMeshUpdate();
int totalVisibleCharacters = m_textMeshPro.textInfo.characterCount; // Get # of Visible Character in text object
int counter = 0;
int visibleCount = 0;
while (true)
{
visibleCount = counter % (totalVisibleCharacters + 1);
m_textMeshPro.maxVisibleCharacters = visibleCount; // How many characters should TextMeshPro display?
// Once the last character has been revealed, wait 1.0 second and start over.
if (visibleCount >= totalVisibleCharacters)
{
yield return new WaitForSeconds(1.0f);
m_textMeshPro.text = label02;
yield return new WaitForSeconds(1.0f);
m_textMeshPro.text = label01;
yield return new WaitForSeconds(1.0f);
}
counter += 1;
yield return new WaitForSeconds(0.05f);
}
//Debug.Log("Done revealing the text.");
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: e32c266ee6204b21a427753cb0694c81
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TextConsoleSimulator : MonoBehaviour
{
private TMP_Text m_TextComponent;
private bool hasTextChanged;
void Awake()
{
m_TextComponent = gameObject.GetComponent<TMP_Text>();
}
void Start()
{
StartCoroutine(RevealCharacters(m_TextComponent));
//StartCoroutine(RevealWords(m_TextComponent));
}
void OnEnable()
{
// Subscribe to event fired when text object has been regenerated.
TMPro_EventManager.TEXT_CHANGED_EVENT.Add(ON_TEXT_CHANGED);
}
void OnDisable()
{
TMPro_EventManager.TEXT_CHANGED_EVENT.Remove(ON_TEXT_CHANGED);
}
// Event received when the text object has changed.
void ON_TEXT_CHANGED(Object obj)
{
hasTextChanged = true;
}
/// <summary>
/// Method revealing the text one character at a time.
/// </summary>
/// <returns></returns>
IEnumerator RevealCharacters(TMP_Text textComponent)
{
textComponent.ForceMeshUpdate();
TMP_TextInfo textInfo = textComponent.textInfo;
int totalVisibleCharacters = textInfo.characterCount; // Get # of Visible Character in text object
int visibleCount = 0;
while (true)
{
if (hasTextChanged)
{
totalVisibleCharacters = textInfo.characterCount; // Update visible character count.
hasTextChanged = false;
}
if (visibleCount > totalVisibleCharacters)
{
yield return new WaitForSeconds(1.0f);
visibleCount = 0;
}
textComponent.maxVisibleCharacters = visibleCount; // How many characters should TextMeshPro display?
visibleCount += 1;
yield return null;
}
}
/// <summary>
/// Method revealing the text one word at a time.
/// </summary>
/// <returns></returns>
IEnumerator RevealWords(TMP_Text textComponent)
{
textComponent.ForceMeshUpdate();
int totalWordCount = textComponent.textInfo.wordCount;
int totalVisibleCharacters = textComponent.textInfo.characterCount; // Get # of Visible Character in text object
int counter = 0;
int currentWord = 0;
int visibleCount = 0;
while (true)
{
currentWord = counter % (totalWordCount + 1);
// Get last character index for the current word.
if (currentWord == 0) // Display no words.
visibleCount = 0;
else if (currentWord < totalWordCount) // Display all other words with the exception of the last one.
visibleCount = textComponent.textInfo.wordInfo[currentWord - 1].lastCharacterIndex + 1;
else if (currentWord == totalWordCount) // Display last word and all remaining characters.
visibleCount = totalVisibleCharacters;
textComponent.maxVisibleCharacters = visibleCount; // How many characters should TextMeshPro display?
// Once the last character has been revealed, wait 1.0 second and start over.
if (visibleCount >= totalVisibleCharacters)
{
yield return new WaitForSeconds(1.0f);
}
counter += 1;
yield return new WaitForSeconds(0.1f);
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 43bcd35a1c0c40ccb6d472893fe2093f
timeCreated: 1435298333
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TextMeshProFloatingText : MonoBehaviour
{
public Font TheFont;
private GameObject m_floatingText;
private TextMeshPro m_textMeshPro;
private TextMesh m_textMesh;
private Transform m_transform;
private Transform m_floatingText_Transform;
private Transform m_cameraTransform;
Vector3 lastPOS = Vector3.zero;
Quaternion lastRotation = Quaternion.identity;
public int SpawnType;
public bool IsTextObjectScaleStatic;
//private int m_frame = 0;
static WaitForEndOfFrame k_WaitForEndOfFrame = new WaitForEndOfFrame();
static WaitForSeconds[] k_WaitForSecondsRandom = new WaitForSeconds[]
{
new WaitForSeconds(0.05f), new WaitForSeconds(0.1f), new WaitForSeconds(0.15f), new WaitForSeconds(0.2f), new WaitForSeconds(0.25f),
new WaitForSeconds(0.3f), new WaitForSeconds(0.35f), new WaitForSeconds(0.4f), new WaitForSeconds(0.45f), new WaitForSeconds(0.5f),
new WaitForSeconds(0.55f), new WaitForSeconds(0.6f), new WaitForSeconds(0.65f), new WaitForSeconds(0.7f), new WaitForSeconds(0.75f),
new WaitForSeconds(0.8f), new WaitForSeconds(0.85f), new WaitForSeconds(0.9f), new WaitForSeconds(0.95f), new WaitForSeconds(1.0f),
};
void Awake()
{
m_transform = transform;
m_floatingText = new GameObject(this.name + " floating text");
// Reference to Transform is lost when TMP component is added since it replaces it by a RectTransform.
//m_floatingText_Transform = m_floatingText.transform;
//m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
m_cameraTransform = Camera.main.transform;
}
void Start()
{
if (SpawnType == 0)
{
// TextMesh Pro Implementation
m_textMeshPro = m_floatingText.AddComponent<TextMeshPro>();
m_textMeshPro.rectTransform.sizeDelta = new Vector2(3, 3);
m_floatingText_Transform = m_floatingText.transform;
m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
//m_textMeshPro.fontAsset = Resources.Load("Fonts & Materials/JOKERMAN SDF", typeof(TextMeshProFont)) as TextMeshProFont; // User should only provide a string to the resource.
//m_textMeshPro.fontSharedMaterial = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(Material)) as Material;
m_textMeshPro.alignment = TextAlignmentOptions.Center;
m_textMeshPro.color = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
m_textMeshPro.fontSize = 24;
//m_textMeshPro.enableExtraPadding = true;
//m_textMeshPro.enableShadows = false;
m_textMeshPro.enableKerning = false;
m_textMeshPro.text = string.Empty;
m_textMeshPro.isTextObjectScaleStatic = IsTextObjectScaleStatic;
StartCoroutine(DisplayTextMeshProFloatingText());
}
else if (SpawnType == 1)
{
//Debug.Log("Spawning TextMesh Objects.");
m_floatingText_Transform = m_floatingText.transform;
m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
m_textMesh = m_floatingText.AddComponent<TextMesh>();
m_textMesh.font = Resources.Load<Font>("Fonts/ARIAL");
m_textMesh.GetComponent<Renderer>().sharedMaterial = m_textMesh.font.material;
m_textMesh.color = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
m_textMesh.anchor = TextAnchor.LowerCenter;
m_textMesh.fontSize = 24;
StartCoroutine(DisplayTextMeshFloatingText());
}
else if (SpawnType == 2)
{
}
}
//void Update()
//{
// if (SpawnType == 0)
// {
// m_textMeshPro.SetText("{0}", m_frame);
// }
// else
// {
// m_textMesh.text = m_frame.ToString();
// }
// m_frame = (m_frame + 1) % 1000;
//}
public IEnumerator DisplayTextMeshProFloatingText()
{
float CountDuration = 2.0f; // How long is the countdown alive.
float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at.
float current_Count = starting_Count;
Vector3 start_pos = m_floatingText_Transform.position;
Color32 start_color = m_textMeshPro.color;
float alpha = 255;
int int_counter = 0;
float fadeDuration = 3 / starting_Count * CountDuration;
while (current_Count > 0)
{
current_Count -= (Time.deltaTime / CountDuration) * starting_Count;
if (current_Count <= 3)
{
//Debug.Log("Fading Counter ... " + current_Count.ToString("f2"));
alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255);
}
int_counter = (int)current_Count;
m_textMeshPro.text = int_counter.ToString();
//m_textMeshPro.SetText("{0}", (int)current_Count);
m_textMeshPro.color = new Color32(start_color.r, start_color.g, start_color.b, (byte)alpha);
// Move the floating text upward each update
m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0);
// Align floating text perpendicular to Camera.
if (!lastPOS.Compare(m_cameraTransform.position, 1000) || !lastRotation.Compare(m_cameraTransform.rotation, 1000))
{
lastPOS = m_cameraTransform.position;
lastRotation = m_cameraTransform.rotation;
m_floatingText_Transform.rotation = lastRotation;
Vector3 dir = m_transform.position - lastPOS;
m_transform.forward = new Vector3(dir.x, 0, dir.z);
}
yield return k_WaitForEndOfFrame;
}
//Debug.Log("Done Counting down.");
yield return k_WaitForSecondsRandom[Random.Range(0, 19)];
m_floatingText_Transform.position = start_pos;
StartCoroutine(DisplayTextMeshProFloatingText());
}
public IEnumerator DisplayTextMeshFloatingText()
{
float CountDuration = 2.0f; // How long is the countdown alive.
float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at.
float current_Count = starting_Count;
Vector3 start_pos = m_floatingText_Transform.position;
Color32 start_color = m_textMesh.color;
float alpha = 255;
int int_counter = 0;
float fadeDuration = 3 / starting_Count * CountDuration;
while (current_Count > 0)
{
current_Count -= (Time.deltaTime / CountDuration) * starting_Count;
if (current_Count <= 3)
{
//Debug.Log("Fading Counter ... " + current_Count.ToString("f2"));
alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255);
}
int_counter = (int)current_Count;
m_textMesh.text = int_counter.ToString();
//Debug.Log("Current Count:" + current_Count.ToString("f2"));
m_textMesh.color = new Color32(start_color.r, start_color.g, start_color.b, (byte)alpha);
// Move the floating text upward each update
m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0);
// Align floating text perpendicular to Camera.
if (!lastPOS.Compare(m_cameraTransform.position, 1000) || !lastRotation.Compare(m_cameraTransform.rotation, 1000))
{
lastPOS = m_cameraTransform.position;
lastRotation = m_cameraTransform.rotation;
m_floatingText_Transform.rotation = lastRotation;
Vector3 dir = m_transform.position - lastPOS;
m_transform.forward = new Vector3(dir.x, 0, dir.z);
}
yield return k_WaitForEndOfFrame;
}
//Debug.Log("Done Counting down.");
yield return k_WaitForSecondsRandom[Random.Range(0, 20)];
m_floatingText_Transform.position = start_pos;
StartCoroutine(DisplayTextMeshFloatingText());
}
}
}
fileFormatVersion: 2
guid: a4d4c76e63944cba8c7d00f56334b98c
MonoImporter:
serializedVersion: 2
defaultReferences:
- TheFont: {instanceID: 0}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment