Commit 1444629e authored by BlackAngle233's avatar BlackAngle233
Browse files

12.22 update UI

the font assets is too large, so not be pushed
parent c4fc982a
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class Benchmark04 : MonoBehaviour
{
public int SpawnType = 0;
public int MinPointSize = 12;
public int MaxPointSize = 64;
public int Steps = 4;
private Transform m_Transform;
//private TextMeshProFloatingText floatingText_Script;
//public Material material;
void Start()
{
m_Transform = transform;
float lineHeight = 0;
float orthoSize = Camera.main.orthographicSize = Screen.height / 2;
float ratio = (float)Screen.width / Screen.height;
for (int i = MinPointSize; i <= MaxPointSize; i += Steps)
{
if (SpawnType == 0)
{
// TextMesh Pro Implementation
GameObject go = new GameObject("Text - " + i + " Pts");
if (lineHeight > orthoSize * 2) return;
go.transform.position = m_Transform.position + new Vector3(ratio * -orthoSize * 0.975f, orthoSize * 0.975f - lineHeight, 0);
TextMeshPro textMeshPro = go.AddComponent<TextMeshPro>();
//textMeshPro.fontSharedMaterial = material;
//textMeshPro.font = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(TextMeshProFont)) as TextMeshProFont;
//textMeshPro.anchor = AnchorPositions.Left;
textMeshPro.rectTransform.pivot = new Vector2(0, 0.5f);
textMeshPro.enableWordWrapping = false;
textMeshPro.extraPadding = true;
textMeshPro.isOrthographic = true;
textMeshPro.fontSize = i;
textMeshPro.text = i + " pts - Lorem ipsum dolor sit...";
textMeshPro.color = new Color32(255, 255, 255, 255);
lineHeight += i;
}
else
{
// TextMesh Implementation
// Causes crashes since atlas needed exceeds 4096 X 4096
/*
GameObject go = new GameObject("Arial " + i);
//if (lineHeight > orthoSize * 2 * 0.9f) return;
go.transform.position = m_Transform.position + new Vector3(ratio * -orthoSize * 0.975f, orthoSize * 0.975f - lineHeight, 1);
TextMesh textMesh = go.AddComponent<TextMesh>();
textMesh.font = Resources.Load("Fonts/ARIAL", typeof(Font)) as Font;
textMesh.renderer.sharedMaterial = textMesh.font.material;
textMesh.anchor = TextAnchor.MiddleLeft;
textMesh.fontSize = i * 10;
textMesh.color = new Color32(255, 255, 255, 255);
textMesh.text = i + " pts - Lorem ipsum dolor sit...";
lineHeight += i;
*/
}
}
}
}
}
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class CameraController : MonoBehaviour
{
public enum CameraModes { Follow, Isometric, Free }
private Transform cameraTransform;
private Transform dummyTarget;
public Transform CameraTarget;
public float FollowDistance = 30.0f;
public float MaxFollowDistance = 100.0f;
public float MinFollowDistance = 2.0f;
public float ElevationAngle = 30.0f;
public float MaxElevationAngle = 85.0f;
public float MinElevationAngle = 0f;
public float OrbitalAngle = 0f;
public CameraModes CameraMode = CameraModes.Follow;
public bool MovementSmoothing = true;
public bool RotationSmoothing = false;
private bool previousSmoothing;
public float MovementSmoothingValue = 25f;
public float RotationSmoothingValue = 5.0f;
public float MoveSensitivity = 2.0f;
private Vector3 currentVelocity = Vector3.zero;
private Vector3 desiredPosition;
private float mouseX;
private float mouseY;
private Vector3 moveVector;
private float mouseWheel;
// Controls for Touches on Mobile devices
//private float prev_ZoomDelta;
private const string event_SmoothingValue = "Slider - Smoothing Value";
private const string event_FollowDistance = "Slider - Camera Zoom";
void Awake()
{
if (QualitySettings.vSyncCount > 0)
Application.targetFrameRate = 60;
else
Application.targetFrameRate = -1;
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
Input.simulateMouseWithTouches = false;
cameraTransform = transform;
previousSmoothing = MovementSmoothing;
}
// Use this for initialization
void Start()
{
if (CameraTarget == null)
{
// If we don't have a target (assigned by the player, create a dummy in the center of the scene).
dummyTarget = new GameObject("Camera Target").transform;
CameraTarget = dummyTarget;
}
}
// Update is called once per frame
void LateUpdate()
{
GetPlayerInput();
// Check if we still have a valid target
if (CameraTarget != null)
{
if (CameraMode == CameraModes.Isometric)
{
desiredPosition = CameraTarget.position + Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * new Vector3(0, 0, -FollowDistance);
}
else if (CameraMode == CameraModes.Follow)
{
desiredPosition = CameraTarget.position + CameraTarget.TransformDirection(Quaternion.Euler(ElevationAngle, OrbitalAngle, 0f) * (new Vector3(0, 0, -FollowDistance)));
}
else
{
// Free Camera implementation
}
if (MovementSmoothing == true)
{
// Using Smoothing
cameraTransform.position = Vector3.SmoothDamp(cameraTransform.position, desiredPosition, ref currentVelocity, MovementSmoothingValue * Time.fixedDeltaTime);
//cameraTransform.position = Vector3.Lerp(cameraTransform.position, desiredPosition, Time.deltaTime * 5.0f);
}
else
{
// Not using Smoothing
cameraTransform.position = desiredPosition;
}
if (RotationSmoothing == true)
cameraTransform.rotation = Quaternion.Lerp(cameraTransform.rotation, Quaternion.LookRotation(CameraTarget.position - cameraTransform.position), RotationSmoothingValue * Time.deltaTime);
else
{
cameraTransform.LookAt(CameraTarget);
}
}
}
void GetPlayerInput()
{
moveVector = Vector3.zero;
// Check Mouse Wheel Input prior to Shift Key so we can apply multiplier on Shift for Scrolling
mouseWheel = Input.GetAxis("Mouse ScrollWheel");
float touchCount = Input.touchCount;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || touchCount > 0)
{
mouseWheel *= 10;
if (Input.GetKeyDown(KeyCode.I))
CameraMode = CameraModes.Isometric;
if (Input.GetKeyDown(KeyCode.F))
CameraMode = CameraModes.Follow;
if (Input.GetKeyDown(KeyCode.S))
MovementSmoothing = !MovementSmoothing;
// Check for right mouse button to change camera follow and elevation angle
if (Input.GetMouseButton(1))
{
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
if (mouseY > 0.01f || mouseY < -0.01f)
{
ElevationAngle -= mouseY * MoveSensitivity;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
if (mouseX > 0.01f || mouseX < -0.01f)
{
OrbitalAngle += mouseX * MoveSensitivity;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Get Input from Mobile Device
if (touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;
// Handle elevation changes
if (deltaPosition.y > 0.01f || deltaPosition.y < -0.01f)
{
ElevationAngle -= deltaPosition.y * 0.1f;
// Limit Elevation angle between min & max values.
ElevationAngle = Mathf.Clamp(ElevationAngle, MinElevationAngle, MaxElevationAngle);
}
// Handle left & right
if (deltaPosition.x > 0.01f || deltaPosition.x < -0.01f)
{
OrbitalAngle += deltaPosition.x * 0.1f;
if (OrbitalAngle > 360)
OrbitalAngle -= 360;
if (OrbitalAngle < 0)
OrbitalAngle += 360;
}
}
// Check for left mouse button to select a new CameraTarget or to reset Follow position
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 300, 1 << 10 | 1 << 11 | 1 << 12 | 1 << 14))
{
if (hit.transform == CameraTarget)
{
// Reset Follow Position
OrbitalAngle = 0;
}
else
{
CameraTarget = hit.transform;
OrbitalAngle = 0;
MovementSmoothing = previousSmoothing;
}
}
}
if (Input.GetMouseButton(2))
{
if (dummyTarget == null)
{
// We need a Dummy Target to anchor the Camera
dummyTarget = new GameObject("Camera Target").transform;
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
else if (dummyTarget != CameraTarget)
{
// Move DummyTarget to CameraTarget
dummyTarget.position = CameraTarget.position;
dummyTarget.rotation = CameraTarget.rotation;
CameraTarget = dummyTarget;
previousSmoothing = MovementSmoothing;
MovementSmoothing = false;
}
mouseY = Input.GetAxis("Mouse Y");
mouseX = Input.GetAxis("Mouse X");
moveVector = cameraTransform.TransformDirection(mouseX, mouseY, 0);
dummyTarget.Translate(-moveVector, Space.World);
}
}
// Check Pinching to Zoom in - out on Mobile device
if (touchCount == 2)
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevTouchDelta = (touch0PrevPos - touch1PrevPos).magnitude;
float touchDelta = (touch0.position - touch1.position).magnitude;
float zoomDelta = prevTouchDelta - touchDelta;
if (zoomDelta > 0.01f || zoomDelta < -0.01f)
{
FollowDistance += zoomDelta * 0.25f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
// Check MouseWheel to Zoom in-out
if (mouseWheel < -0.01f || mouseWheel > 0.01f)
{
FollowDistance -= mouseWheel * 5.0f;
// Limit FollowDistance between min & max values.
FollowDistance = Mathf.Clamp(FollowDistance, MinFollowDistance, MaxFollowDistance);
}
}
}
}
\ No newline at end of file
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;
public class ChatController : MonoBehaviour {
public TMP_InputField TMP_ChatInput;
public TMP_Text TMP_ChatOutput;
public Scrollbar ChatScrollbar;
void OnEnable()
{
TMP_ChatInput.onSubmit.AddListener(AddToChatOutput);
}
void OnDisable()
{
TMP_ChatInput.onSubmit.RemoveListener(AddToChatOutput);
}
void AddToChatOutput(string newText)
{
// Clear Input Field
TMP_ChatInput.text = string.Empty;
var timeNow = System.DateTime.Now;
TMP_ChatOutput.text += "[<#FFFF80>" + timeNow.Hour.ToString("d2") + ":" + timeNow.Minute.ToString("d2") + ":" + timeNow.Second.ToString("d2") + "</color>] " + newText + "\n";
TMP_ChatInput.ActivateInputField();
// Set the scrollbar to the bottom when next text is submitted.
ChatScrollbar.value = 0;
}
}
using UnityEngine;
using System.Collections;
using TMPro;
public class EnvMapAnimator : MonoBehaviour {
//private Vector3 TranslationSpeeds;
public Vector3 RotationSpeeds;
private TMP_Text m_textMeshPro;
private Material m_material;
void Awake()
{
//Debug.Log("Awake() on Script called.");
m_textMeshPro = GetComponent<TMP_Text>();
m_material = m_textMeshPro.fontSharedMaterial;
}
// Use this for initialization
IEnumerator Start ()
{
Matrix4x4 matrix = new Matrix4x4();
while (true)
{
//matrix.SetTRS(new Vector3 (Time.time * TranslationSpeeds.x, Time.time * TranslationSpeeds.y, Time.time * TranslationSpeeds.z), Quaternion.Euler(Time.time * RotationSpeeds.x, Time.time * RotationSpeeds.y , Time.time * RotationSpeeds.z), Vector3.one);
matrix.SetTRS(Vector3.zero, Quaternion.Euler(Time.time * RotationSpeeds.x, Time.time * RotationSpeeds.y , Time.time * RotationSpeeds.z), Vector3.one);
m_material.SetMatrix("_EnvMatrix", matrix);
yield return null;
}
}
}
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class ObjectSpin : MonoBehaviour
{
#pragma warning disable 0414
public float SpinSpeed = 5;
public int RotationRange = 15;
private Transform m_transform;
private float m_time;
private Vector3 m_prevPOS;
private Vector3 m_initial_Rotation;
private Vector3 m_initial_Position;
private Color32 m_lightColor;
private int frames = 0;
public enum MotionType { Rotation, BackAndForth, Translation };
public MotionType Motion;
void Awake()
{
m_transform = transform;
m_initial_Rotation = m_transform.rotation.eulerAngles;
m_initial_Position = m_transform.position;
Light light = GetComponent<Light>();
m_lightColor = light != null ? light.color : Color.black;
}
// Update is called once per frame
void Update()
{
if (Motion == MotionType.Rotation)
{
m_transform.Rotate(0, SpinSpeed * Time.deltaTime, 0);
}
else if (Motion == MotionType.BackAndForth)
{
m_time += SpinSpeed * Time.deltaTime;
m_transform.rotation = Quaternion.Euler(m_initial_Rotation.x, Mathf.Sin(m_time) * RotationRange + m_initial_Rotation.y, m_initial_Rotation.z);
}
else
{
m_time += SpinSpeed * Time.deltaTime;
float x = 15 * Mathf.Cos(m_time * .95f);
float y = 10; // *Mathf.Sin(m_time * 1f) * Mathf.Cos(m_time * 1f);
float z = 0f; // *Mathf.Sin(m_time * .9f);
m_transform.position = m_initial_Position + new Vector3(x, z, y);
// Drawing light patterns because they can be cool looking.
//if (frames > 2)
// Debug.DrawLine(m_transform.position, m_prevPOS, m_lightColor, 100f);
m_prevPOS = m_transform.position;
frames += 1;
}
}
}
}
\ No newline at end of file
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class ShaderPropAnimator : MonoBehaviour
{
private Renderer m_Renderer;
private Material m_Material;
public AnimationCurve GlowCurve;
public float m_frame;
void Awake()
{
// Cache a reference to object's renderer
m_Renderer = GetComponent<Renderer>();
// Cache a reference to object's material and create an instance by doing so.
m_Material = m_Renderer.material;
}
void Start()
{
StartCoroutine(AnimateProperties());
}
IEnumerator AnimateProperties()
{
//float lightAngle;
float glowPower;
m_frame = Random.Range(0f, 1f);
while (true)
{
//lightAngle = (m_Material.GetFloat(ShaderPropertyIDs.ID_LightAngle) + Time.deltaTime) % 6.2831853f;
//m_Material.SetFloat(ShaderPropertyIDs.ID_LightAngle, lightAngle);
glowPower = GlowCurve.Evaluate(m_frame);
m_Material.SetFloat(ShaderUtilities.ID_GlowPower, glowPower);
m_frame += Time.deltaTime * Random.Range(0.2f, 0.3f);
yield return new WaitForEndOfFrame();
}
}
}
}
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class SimpleScript : MonoBehaviour
{
private TextMeshPro m_textMeshPro;
//private TMP_FontAsset m_FontAsset;
private const string label = "The <#0050FF>count is: </color>{0:2}";
private float m_frame;
void Start()
{
// Add new TextMesh Pro Component
m_textMeshPro = gameObject.AddComponent<TextMeshPro>();
m_textMeshPro.autoSizeTextContainer = true;
// Load the Font Asset to be used.
//m_FontAsset = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(TMP_FontAsset)) as TMP_FontAsset;
//m_textMeshPro.font = m_FontAsset;
// Assign Material to TextMesh Pro Component
//m_textMeshPro.fontSharedMaterial = Resources.Load("Fonts & Materials/LiberationSans SDF - Bevel", typeof(Material)) as Material;
//m_textMeshPro.fontSharedMaterial.EnableKeyword("BEVEL_ON");
// Set various font settings.
m_textMeshPro.fontSize = 48;
m_textMeshPro.alignment = TextAlignmentOptions.Center;
//m_textMeshPro.anchorDampening = true; // Has been deprecated but under consideration for re-implementation.
//m_textMeshPro.enableAutoSizing = true;
//m_textMeshPro.characterSpacing = 0.2f;
//m_textMeshPro.wordSpacing = 0.1f;
//m_textMeshPro.enableCulling = true;
m_textMeshPro.enableWordWrapping = false;
//textMeshPro.fontColor = new Color32(255, 255, 255, 255);
}
void Update()
{
m_textMeshPro.SetText(label, m_frame % 1000);
m_frame += 1 * Time.deltaTime;
}
}
}
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class SkewTextExample : MonoBehaviour
{
private TMP_Text m_TextComponent;
public AnimationCurve VertexCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(0.25f, 2.0f), new Keyframe(0.5f, 0), new Keyframe(0.75f, 2.0f), new Keyframe(1, 0f));
//public float AngleMultiplier = 1.0f;
//public float SpeedMultiplier = 1.0f;
public float CurveScale = 1.0f;
public float ShearAmount = 1.0f;
void Awake()
{
m_TextComponent = gameObject.GetComponent<TMP_Text>();
}
void Start()
{
StartCoroutine(WarpText());
}
private AnimationCurve CopyAnimationCurve(AnimationCurve curve)
{
AnimationCurve newCurve = new AnimationCurve();
newCurve.keys = curve.keys;
return newCurve;
}
/// <summary>
/// Method to curve text along a Unity animation curve.
/// </summary>
/// <param name="textComponent"></param>
/// <returns></returns>
IEnumerator WarpText()
{
VertexCurve.preWrapMode = WrapMode.Clamp;
VertexCurve.postWrapMode = WrapMode.Clamp;
//Mesh mesh = m_TextComponent.textInfo.meshInfo[0].mesh;
Vector3[] vertices;
Matrix4x4 matrix;
m_TextComponent.havePropertiesChanged = true; // Need to force the TextMeshPro Object to be updated.
CurveScale *= 10;
float old_CurveScale = CurveScale;
float old_ShearValue = ShearAmount;
AnimationCurve old_curve = CopyAnimationCurve(VertexCurve);
while (true)
{
if (!m_TextComponent.havePropertiesChanged && old_CurveScale == CurveScale && old_curve.keys[1].value == VertexCurve.keys[1].value && old_ShearValue == ShearAmount)
{
yield return null;
continue;
}
old_CurveScale = CurveScale;
old_curve = CopyAnimationCurve(VertexCurve);
old_ShearValue = ShearAmount;
m_TextComponent.ForceMeshUpdate(); // Generate the mesh and populate the textInfo with data we can use and manipulate.
TMP_TextInfo textInfo = m_TextComponent.textInfo;
int characterCount = textInfo.characterCount;
if (characterCount == 0) continue;
//vertices = textInfo.meshInfo[0].vertices;
//int lastVertexIndex = textInfo.characterInfo[characterCount - 1].vertexIndex;
float boundsMinX = m_TextComponent.bounds.min.x; //textInfo.meshInfo[0].mesh.bounds.min.x;
float boundsMaxX = m_TextComponent.bounds.max.x; //textInfo.meshInfo[0].mesh.bounds.max.x;
for (int i = 0; i < characterCount; i++)
{
if (!textInfo.characterInfo[i].isVisible)
continue;
int vertexIndex = textInfo.characterInfo[i].vertexIndex;
// Get the index of the mesh used by this character.
int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
vertices = textInfo.meshInfo[materialIndex].vertices;
// Compute the baseline mid point for each character
Vector3 offsetToMidBaseline = new Vector2((vertices[vertexIndex + 0].x + vertices[vertexIndex + 2].x) / 2, textInfo.characterInfo[i].baseLine);
//float offsetY = VertexCurve.Evaluate((float)i / characterCount + loopCount / 50f); // Random.Range(-0.25f, 0.25f);
// Apply offset to adjust our pivot point.
vertices[vertexIndex + 0] += -offsetToMidBaseline;
vertices[vertexIndex + 1] += -offsetToMidBaseline;
vertices[vertexIndex + 2] += -offsetToMidBaseline;
vertices[vertexIndex + 3] += -offsetToMidBaseline;
// Apply the Shearing FX
float shear_value = ShearAmount * 0.01f;
Vector3 topShear = new Vector3(shear_value * (textInfo.characterInfo[i].topRight.y - textInfo.characterInfo[i].baseLine), 0, 0);
Vector3 bottomShear = new Vector3(shear_value * (textInfo.characterInfo[i].baseLine - textInfo.characterInfo[i].bottomRight.y), 0, 0);
vertices[vertexIndex + 0] += -bottomShear;
vertices[vertexIndex + 1] += topShear;
vertices[vertexIndex + 2] += topShear;
vertices[vertexIndex + 3] += -bottomShear;
// Compute the angle of rotation for each character based on the animation curve
float x0 = (offsetToMidBaseline.x - boundsMinX) / (boundsMaxX - boundsMinX); // Character's position relative to the bounds of the mesh.
float x1 = x0 + 0.0001f;
float y0 = VertexCurve.Evaluate(x0) * CurveScale;
float y1 = VertexCurve.Evaluate(x1) * CurveScale;
Vector3 horizontal = new Vector3(1, 0, 0);
//Vector3 normal = new Vector3(-(y1 - y0), (x1 * (boundsMaxX - boundsMinX) + boundsMinX) - offsetToMidBaseline.x, 0);
Vector3 tangent = new Vector3(x1 * (boundsMaxX - boundsMinX) + boundsMinX, y1) - new Vector3(offsetToMidBaseline.x, y0);
float dot = Mathf.Acos(Vector3.Dot(horizontal, tangent.normalized)) * 57.2957795f;
Vector3 cross = Vector3.Cross(horizontal, tangent);
float angle = cross.z > 0 ? dot : 360 - dot;
matrix = Matrix4x4.TRS(new Vector3(0, y0, 0), Quaternion.Euler(0, 0, angle), Vector3.one);
vertices[vertexIndex + 0] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 0]);
vertices[vertexIndex + 1] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]);
vertices[vertexIndex + 2] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]);
vertices[vertexIndex + 3] = matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]);
vertices[vertexIndex + 0] += offsetToMidBaseline;
vertices[vertexIndex + 1] += offsetToMidBaseline;
vertices[vertexIndex + 2] += offsetToMidBaseline;
vertices[vertexIndex + 3] += offsetToMidBaseline;
}
// Upload the mesh with the revised information
m_TextComponent.UpdateVertexData();
yield return null; // new WaitForSeconds(0.025f);
}
}
}
}
using UnityEngine;
using System;
namespace TMPro
{
/// <summary>
/// EXample of a Custom Character Input Validator to only allow digits from 0 to 9.
/// </summary>
[Serializable]
//[CreateAssetMenu(fileName = "InputValidator - Digits.asset", menuName = "TextMeshPro/Input Validators/Digits", order = 100)]
public class TMP_DigitValidator : TMP_InputValidator
{
// Custom text input validation function
public override char Validate(ref string text, ref int pos, char ch)
{
if (ch >= '0' && ch <= '9')
{
pos += 1;
return ch;
}
return (char)0;
}
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;
namespace TMPro.Examples
{
public class TMP_ExampleScript_01 : MonoBehaviour
{
public enum objectType { TextMeshPro = 0, TextMeshProUGUI = 1 };
public objectType ObjectType;
public bool isStatic;
private TMP_Text m_text;
//private TMP_InputField m_inputfield;
private const string k_label = "The count is <#0080ff>{0}</color>";
private int count;
void Awake()
{
// Get a reference to the TMP text component if one already exists otherwise add one.
// This example show the convenience of having both TMP components derive from TMP_Text.
if (ObjectType == 0)
m_text = GetComponent<TextMeshPro>() ?? gameObject.AddComponent<TextMeshPro>();
else
m_text = GetComponent<TextMeshProUGUI>() ?? gameObject.AddComponent<TextMeshProUGUI>();
// Load a new font asset and assign it to the text object.
m_text.font = Resources.Load<TMP_FontAsset>("Fonts & Materials/Anton SDF");
// Load a new material preset which was created with the context menu duplicate.
m_text.fontSharedMaterial = Resources.Load<Material>("Fonts & Materials/Anton SDF - Drop Shadow");
// Set the size of the font.
m_text.fontSize = 120;
// Set the text
m_text.text = "A <#0080ff>simple</color> line of text.";
// Get the preferred width and height based on the supplied width and height as opposed to the actual size of the current text container.
Vector2 size = m_text.GetPreferredValues(Mathf.Infinity, Mathf.Infinity);
// Set the size of the RectTransform based on the new calculated values.
m_text.rectTransform.sizeDelta = new Vector2(size.x, size.y);
}
void Update()
{
if (!isStatic)
{
m_text.SetText(k_label, count % 1000);
count += 1;
}
}
}
}
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TMP_FrameRateCounter : 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 TextMeshPro m_TextMeshPro;
private Transform m_frameCounter_transform;
private Camera m_camera;
private FpsCounterAnchorPositions last_AnchorPosition;
void Awake()
{
if (!enabled)
return;
m_camera = Camera.main;
Application.targetFrameRate = -1;
GameObject frameCounter = new GameObject("Frame Counter");
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_frameCounter_transform = frameCounter.transform;
m_frameCounter_transform.SetParent(m_camera.transform);
m_frameCounter_transform.localRotation = Quaternion.identity;
m_TextMeshPro.enableWordWrapping = false;
m_TextMeshPro.fontSize = 24;
//m_TextMeshPro.FontColor = new Color32(255, 255, 255, 128);
//m_TextMeshPro.edgeWidth = .15f;
m_TextMeshPro.isOverlay = true;
//m_TextMeshPro.FaceColor = new Color32(255, 128, 0, 0);
//m_TextMeshPro.EdgeColor = new Color32(0, 255, 0, 255);
//m_TextMeshPro.FontMaterial.renderQueue = 4000;
//m_TextMeshPro.CreateSoftShadowClone(new Vector2(1f, -1f));
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>";
//string format = System.String.Format(htmlColorTag + "{0:F2} </color>FPS \n{1:F2} <#8080ff>MS",fps, ms);
//m_TextMeshPro.text = format;
m_TextMeshPro.SetText(htmlColorTag + fpsLabel, fps, ms);
m_Frames = 0;
m_LastInterval = timeNow;
}
}
void Set_FrameCounter_Position(FpsCounterAnchorPositions anchor_position)
{
//Debug.Log("Changing frame counter anchor position.");
m_TextMeshPro.margin = new Vector4(1f, 1f, 1f, 1f);
switch (anchor_position)
{
case FpsCounterAnchorPositions.TopLeft:
m_TextMeshPro.alignment = TextAlignmentOptions.TopLeft;
m_TextMeshPro.rectTransform.pivot = new Vector2(0, 1);
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomLeft:
m_TextMeshPro.alignment = TextAlignmentOptions.BottomLeft;
m_TextMeshPro.rectTransform.pivot = new Vector2(0, 0);
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(0, 0, 100.0f));
break;
case FpsCounterAnchorPositions.TopRight:
m_TextMeshPro.alignment = TextAlignmentOptions.TopRight;
m_TextMeshPro.rectTransform.pivot = new Vector2(1, 1);
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 1, 100.0f));
break;
case FpsCounterAnchorPositions.BottomRight:
m_TextMeshPro.alignment = TextAlignmentOptions.BottomRight;
m_TextMeshPro.rectTransform.pivot = new Vector2(1, 0);
m_frameCounter_transform.position = m_camera.ViewportToWorldPoint(new Vector3(1, 0, 100.0f));
break;
}
}
}
}
\ No newline at end of file
using UnityEngine;
using System.Collections;
using System;
namespace TMPro
{
/// <summary>
/// Example of a Custom Character Input Validator to only allow phone number in the (800) 555-1212 format.
/// </summary>
[Serializable]
//[CreateAssetMenu(fileName = "InputValidator - Phone Numbers.asset", menuName = "TextMeshPro/Input Validators/Phone Numbers")]
public class TMP_PhoneNumberValidator : TMP_InputValidator
{
// Custom text input validation function
public override char Validate(ref string text, ref int pos, char ch)
{
Debug.Log("Trying to validate...");
// Return unless the character is a valid digit
if (ch < '0' && ch > '9') return (char)0;
int length = text.Length;
// Enforce Phone Number format for every character input.
for (int i = 0; i < length + 1; i++)
{
switch (i)
{
case 0:
if (i == length)
text = "(" + ch;
pos = 2;
break;
case 1:
if (i == length)
text += ch;
pos = 2;
break;
case 2:
if (i == length)
text += ch;
pos = 3;
break;
case 3:
if (i == length)
text += ch + ") ";
pos = 6;
break;
case 4:
if (i == length)
text += ") " + ch;
pos = 7;
break;
case 5:
if (i == length)
text += " " + ch;
pos = 7;
break;
case 6:
if (i == length)
text += ch;
pos = 7;
break;
case 7:
if (i == length)
text += ch;
pos = 8;
break;
case 8:
if (i == length)
text += ch + "-";
pos = 10;
break;
case 9:
if (i == length)
text += "-" + ch;
pos = 11;
break;
case 10:
if (i == length)
text += ch;
pos = 11;
break;
case 11:
if (i == length)
text += ch;
pos = 12;
break;
case 12:
if (i == length)
text += ch;
pos = 13;
break;
case 13:
if (i == length)
text += ch;
pos = 14;
break;
}
}
return ch;
}
}
}
using UnityEngine;
namespace TMPro.Examples
{
public class TMP_TextEventCheck : MonoBehaviour
{
public TMP_TextEventHandler TextEventHandler;
void OnEnable()
{
if (TextEventHandler != null)
{
TextEventHandler.onCharacterSelection.AddListener(OnCharacterSelection);
TextEventHandler.onSpriteSelection.AddListener(OnSpriteSelection);
TextEventHandler.onWordSelection.AddListener(OnWordSelection);
TextEventHandler.onLineSelection.AddListener(OnLineSelection);
TextEventHandler.onLinkSelection.AddListener(OnLinkSelection);
}
}
void OnDisable()
{
if (TextEventHandler != null)
{
TextEventHandler.onCharacterSelection.RemoveListener(OnCharacterSelection);
TextEventHandler.onSpriteSelection.RemoveListener(OnSpriteSelection);
TextEventHandler.onWordSelection.RemoveListener(OnWordSelection);
TextEventHandler.onLineSelection.RemoveListener(OnLineSelection);
TextEventHandler.onLinkSelection.RemoveListener(OnLinkSelection);
}
}
void OnCharacterSelection(char c, int index)
{
Debug.Log("Character [" + c + "] at Index: " + index + " has been selected.");
}
void OnSpriteSelection(char c, int index)
{
Debug.Log("Sprite [" + c + "] at Index: " + index + " has been selected.");
}
void OnWordSelection(string word, int firstCharacterIndex, int length)
{
Debug.Log("Word [" + word + "] with first character index of " + firstCharacterIndex + " and length of " + length + " has been selected.");
}
void OnLineSelection(string lineText, int firstCharacterIndex, int length)
{
Debug.Log("Line [" + lineText + "] with first character index of " + firstCharacterIndex + " and length of " + length + " has been selected.");
}
void OnLinkSelection(string linkID, string linkText, int linkIndex)
{
Debug.Log("Link Index: " + linkIndex + " with ID [" + linkID + "] and Text \"" + linkText + "\" has been selected.");
}
}
}
\ No newline at end of file
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
}
}
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);
}
}
}
using UnityEngine;
using System.Collections;
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;
[SerializeField]
private Transform m_Transform;
void OnDrawGizmos()
{
if (m_TextComponent == null)
{
m_TextComponent = gameObject.GetComponent<TMP_Text>();
if (m_TextComponent == null)
return;
if (m_Transform == null)
m_Transform = gameObject.GetComponent<Transform>();
}
// Update Text Statistics
TMP_TextInfo textInfo = m_TextComponent.textInfo;
ObjectStats = "Characters: " + textInfo.characterCount + " Words: " + textInfo.wordCount + " Spaces: " + textInfo.spaceCount + " Sprites: " + textInfo.spriteCount + " Links: " + textInfo.linkCount
+ "\nLines: " + textInfo.lineCount + " Pages: " + textInfo.pageCount;
// Draw Quads around each of the Characters
#region Draw Characters
if (ShowCharacters)
DrawCharactersBounds();
#endregion
// Draw Quads around each of the words
#region Draw Words
if (ShowWords)
DrawWordBounds();
#endregion
// Draw Quads around each of the words
#region Draw Links
if (ShowLinks)
DrawLinkBounds();
#endregion
// Draw Quads around each line
#region Draw Lines
if (ShowLines)
DrawLineBounds();
#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()
{
TMP_TextInfo textInfo = m_TextComponent.textInfo;
for (int i = 0; i < textInfo.characterCount; i++)
{
// Draw visible as well as invisible characters
TMP_CharacterInfo cInfo = textInfo.characterInfo[i];
bool isCharacterVisible = i >= m_TextComponent.maxVisibleCharacters ||
cInfo.lineNumber >= m_TextComponent.maxVisibleLines ||
(m_TextComponent.overflowMode == TextOverflowModes.Page && cInfo.pageNumber + 1 != m_TextComponent.pageToDisplay) ? false : true;
if (!isCharacterVisible) continue;
// Get Bottom Left and Top Right position of the current character
Vector3 bottomLeft = m_Transform.TransformPoint(cInfo.bottomLeft);
Vector3 topLeft = m_Transform.TransformPoint(new Vector3(cInfo.topLeft.x, cInfo.topLeft.y, 0));
Vector3 topRight = m_Transform.TransformPoint(cInfo.topRight);
Vector3 bottomRight = m_Transform.TransformPoint(new Vector3(cInfo.bottomRight.x, cInfo.bottomRight.y, 0));
Color color = cInfo.isVisible ? Color.yellow : Color.grey;
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, color);
// Baseline
Vector3 baselineStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, cInfo.baseLine, 0)).y, 0);
Vector3 baselineEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, cInfo.baseLine, 0)).y, 0);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(baselineStart, baselineEnd);
// Draw Ascender & Descender for each character.
Vector3 ascenderStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, cInfo.ascender, 0)).y, 0);
Vector3 ascenderEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, cInfo.ascender, 0)).y, 0);
Vector3 descenderStart = new Vector3(bottomLeft.x, m_Transform.TransformPoint(new Vector3(0, cInfo.descender, 0)).y, 0);
Vector3 descenderEnd = new Vector3(bottomRight.x, m_Transform.TransformPoint(new Vector3(0, cInfo.descender, 0)).y, 0);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(ascenderStart, ascenderEnd);
Gizmos.DrawLine(descenderStart, descenderEnd);
// Draw Cap Height
float capHeight = cInfo.baseLine + cInfo.fontAsset.faceInfo.capLine * cInfo.scale;
Vector3 capHeightStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, capHeight, 0)).y, 0);
Vector3 capHeightEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, capHeight, 0)).y, 0);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(capHeightStart, capHeightEnd);
// Draw Centerline
float meanline = cInfo.baseLine + cInfo.fontAsset.faceInfo.meanLine * cInfo.scale;
Vector3 centerlineStart = new Vector3(topLeft.x, m_Transform.TransformPoint(new Vector3(0, meanline, 0)).y, 0);
Vector3 centerlineEnd = new Vector3(topRight.x, m_Transform.TransformPoint(new Vector3(0, meanline, 0)).y, 0);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(centerlineStart, centerlineEnd);
// Draw Origin for each character.
float gizmoSize = (ascenderEnd.y - descenderEnd.y) * 0.02f;
Vector3 origin = m_Transform.TransformPoint(cInfo.origin, cInfo.baseLine, 0);
Vector3 originBL = new Vector3(origin.x - gizmoSize, origin.y - gizmoSize, 0);
Vector3 originTL = new Vector3(originBL.x, origin.y + gizmoSize, 0);
Vector3 originTR = new Vector3(origin.x + gizmoSize, originTL.y, 0);
Vector3 originBR = new Vector3(originTR.x, originBL.y, 0);
Gizmos.color = new Color(1, 0.5f, 0);
Gizmos.DrawLine(originBL, originTL);
Gizmos.DrawLine(originTL, originTR);
Gizmos.DrawLine(originTR, originBR);
Gizmos.DrawLine(originBR, originBL);
// Draw xAdvance for each character.
gizmoSize = (ascenderEnd.y - descenderEnd.y) * 0.04f;
float xAdvance = m_Transform.TransformPoint(cInfo.xAdvance, 0, 0).x;
Vector3 topAdvance = new Vector3(xAdvance, baselineStart.y + gizmoSize, 0);
Vector3 bottomAdvance = new Vector3(xAdvance, baselineStart.y - gizmoSize, 0);
Vector3 leftAdvance = new Vector3(xAdvance - gizmoSize, baselineStart.y, 0);
Vector3 rightAdvance = new Vector3(xAdvance + gizmoSize, baselineStart.y, 0);
Gizmos.color = Color.green;
Gizmos.DrawLine(topAdvance, bottomAdvance);
Gizmos.DrawLine(leftAdvance, rightAdvance);
}
}
/// <summary>
/// Method to draw rectangles around each word of the text.
/// </summary>
/// <param name="text"></param>
void DrawWordBounds()
{
TMP_TextInfo textInfo = m_TextComponent.textInfo;
for (int i = 0; i < textInfo.wordCount; i++)
{
TMP_WordInfo wInfo = 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 = 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 != 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()
{
TMP_TextInfo textInfo = m_TextComponent.textInfo;
for (int i = 0; i < textInfo.lineCount; i++)
{
TMP_LineInfo lineInfo = textInfo.lineInfo[i];
bool isLineVisible = (lineInfo.characterCount == 1 && textInfo.characterInfo[lineInfo.firstCharacterIndex].character == 10) ||
i > m_TextComponent.maxVisibleLines ||
(m_TextComponent.overflowMode == TextOverflowModes.Page && textInfo.characterInfo[lineInfo.firstCharacterIndex].pageNumber + 1 != m_TextComponent.pageToDisplay) ? false : true;
if (!isLineVisible) continue;
//if (!ShowLinesOnlyVisibleCharacters)
//{
// Get Bottom Left and Top Right position of each line
float ascender = lineInfo.ascender;
float descender = lineInfo.descender;
float baseline = lineInfo.baseline;
float maxAdvance = lineInfo.maxAdvance;
Vector3 bottomLeft = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].bottomLeft.x, descender, 0));
Vector3 topLeft = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].bottomLeft.x, ascender, 0));
Vector3 topRight = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastCharacterIndex].topRight.x, ascender, 0));
Vector3 bottomRight = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastCharacterIndex].topRight.x, descender, 0));
DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, Color.green);
Vector3 bottomOrigin = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].origin, descender, 0));
Vector3 topOrigin = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].origin, ascender, 0));
Vector3 bottomAdvance = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].origin + maxAdvance, descender, 0));
Vector3 topAdvance = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].origin + maxAdvance, ascender, 0));
DrawDottedRectangle(bottomOrigin, topOrigin, topAdvance, bottomAdvance, Color.green);
Vector3 baselineStart = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstCharacterIndex].bottomLeft.x, baseline, 0));
Vector3 baselineEnd = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastCharacterIndex].topRight.x, baseline, 0));
Gizmos.color = Color.cyan;
Gizmos.DrawLine(baselineStart, baselineEnd);
// Draw LineExtents
Gizmos.color = Color.grey;
Gizmos.DrawLine(m_Transform.TransformPoint(lineInfo.lineExtents.min), m_Transform.TransformPoint(lineInfo.lineExtents.max));
//}
//else
//{
//// Get Bottom Left and Top Right position of each line
//float ascender = lineInfo.ascender;
//float descender = lineInfo.descender;
//Vector3 bottomLeft = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstVisibleCharacterIndex].bottomLeft.x, descender, 0));
//Vector3 topLeft = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstVisibleCharacterIndex].bottomLeft.x, ascender, 0));
//Vector3 topRight = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastVisibleCharacterIndex].topRight.x, ascender, 0));
//Vector3 bottomRight = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastVisibleCharacterIndex].topRight.x, descender, 0));
//DrawRectangle(bottomLeft, topLeft, topRight, bottomRight, Color.green);
//Vector3 baselineStart = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.firstVisibleCharacterIndex].bottomLeft.x, textInfo.characterInfo[lineInfo.firstVisibleCharacterIndex].baseLine, 0));
//Vector3 baselineEnd = m_Transform.TransformPoint(new Vector3(textInfo.characterInfo[lineInfo.lastVisibleCharacterIndex].topRight.x, textInfo.characterInfo[lineInfo.lastVisibleCharacterIndex].baseLine, 0));
//Gizmos.color = Color.cyan;
//Gizmos.DrawLine(baselineStart, baselineEnd);
//}
}
}
/// <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.center - meshBounds.extents);
Vector3 topRight = m_TextComponent.transform.position + (meshBounds.center + meshBounds.extents);
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));
}
// 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
}
}
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;
}
}
}
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);
}
}
}
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
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;
}
}
}
}
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
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