Tmpro unity как включить

от admin

TextMeshPro

com.unity.textmeshpro

Description

TextMeshPro is the ultimate text solution for Unity. It’s the perfect replacement for Unity’s UI Text and the legacy Text Mesh.

Powerful and easy to use, TextMeshPro (also known as TMP) uses Advanced Text Rendering techniques along with a set of custom shaders; delivering substantial visual quality improvements while giving users incredible flexibility when it comes to text styling and texturing.

TextMeshPro provides Improved Control over text formatting and layout with features like character, word, line and paragraph spacing, kerning, justified text, Links, over 30 Rich Text Tags available, support for Multi Font & Sprites, Custom Styles and more.

Great performance. Since the geometry created by TextMeshPro uses two triangles per character just like Unity’s text components, this improved visual quality and flexibility comes at no additional performance cost.

Tmpro unity как включить

TextMeshPro is the ultimate text solution for Unity. It’s the perfect replacement for Unity’s UI Text and the legacy Text Mesh.

Powerful and easy to use, TextMeshPro (also known as TMP) uses Advanced Text Rendering techniques along with a set of custom shaders; delivering substantial visual quality improvements while giving users incredible flexibility when it comes to text styling and texturing.

TextMeshPro provides Improved Control over text formatting and layout with features like character, word, line and paragraph spacing, kerning, justified text, Links, over 30 Rich Text Tags available, support for Multi Font & Sprites, Custom Styles and more.

Great performance. Since the geometry created by TextMeshPro uses two triangles per character just like Unity’s text components, this improved visual quality and flexibility comes at no additional performance cost.

Установка, добавление, настройка шрифтов с кириллицей в плагин TMPro(TextMeshPro) в Unity

How to Make Damage Text Popups in Unity

Making damage numbers or damage text popups appear above a sprite in Unity, at first glance, seems like a simple one. There are definitely many approaches to this, but one must beware of inefficient, resource intensive or bug-prone solutions.

Motivation — Some Bad Methods
UI Animation

Due to how strongly integrated text and Unity UI are, it seems obvious that a first solution is to render a simple “UIText” object above an enemy sprite — that is, a fully UI based solution. This comes with the rather significant problem of mapping the UI space to the world space, as an enemy at (0,0,0) in world space might have completely different coordinates to place UI on.

Additionally, since the UI Canvas is usually linked to a Camera, if you have a moving camera (say, in a platformer or top down shooter) that tracks the player, you’ll have to offset the position of the text to compensate for the camera motion. Zooming and rotation of the camera produce an even larger problem. Here, by following the UI solution, we need to produce two mappings — World Space to the Moving Camera Space, then from a Moving Camera space to a static camera space, with position, rotation and scaling offsets attuned to the time of instantiation. It’s just too much.

Hardcoding

Instead of this solution, you might also choose to “hardcode” text sprites, and instantiate individual letters or words as sprites, rather than UIText, but this lacks flexibility and requires you to make a new sprite for each number and word, and essentially recreate the whole business of rendering text from sprites of characters (eg. a font) from scratch. I feel like this also is an incorrect approach.

The purpose of this article is to present a better solution to this problem, by leveraging TextMeshPro, and compares the efficacy of Unity’s built in Animation suite, and a procedural, code based approach to the problem.

How Do I Create Floating Damage Text Indicators in Unity?

A solution that I have been using is by using objects that share the Global coordinates that the rest of your game is in, but preserves the flexibility of working with a text processing engine, complete with Rich Text support and myriad additional features. Unity does have a built in “TextMesh” 3D object, but I think that TextMeshPro is the better alternative. It requires first a quick import, and is packaged (free of charge) with the Unity Engine.

Overview

At a high level, we’ll be creating a customizable text object, which will be instantiated above our enemy when our it is damaged. After the text object is instantiated, it will float up and disappear, and then remove itself from the scene by calling Destroy() on itself.

This is the order of events:

  1. EnemyTakesDamage()
  2. Instantiate(TextObject parented to Enemy)
  3. FloatAndFade(TextObject)/Use Unity Animation
  4. Destroy(TextObject)/Animation Event
Video
Text Tutorial
Setup

This can be installed through the Unity Package Manager (Menu Bar > Window > Package Manager > TextMeshPro > Install).

Then, you can add a non UI text component by going to the menu bar, and creating a GameObject > 3D > Text / TextMeshPro. This will prompt the import of TMP Essentials, which includes a default font and some other useful starting assets, all nested away in a separate folder that you won’t have to worry about.

You can customize this text component to say whatever you like by editing the Text field in the inspector, and you should disable wrapping as this effect is, in my opinion, undesirable in a text popup effect.

Before animating, we should clearly define what sort of effect we’re looking for. My effect will shrink, fade out and move upwards as time passes, eventually becoming invisible by which time it will be destroyed. Let’s break down these effects individually:

To make an object shrink, we must reduce its scale, but for text we can reduce the font size. The default justification is to the upper left corner of the textbox, and I don’t think this looks good as the text appears to translate as you reduce its font size. To prevent this unpredictable scaling, you can set the justification to be centered on both axes.

Fadeout is as simple as setting the Vertex Colour’s alpha to zero, and upwards movement is an increase in the Y coordinate (in 2D space). These are all the required fields for animating.

Why Use Parents?

If we use Unity animation, we must use a Parent gameobject, to hold our text. This is because Unity animation, as far as I know, cannot handle animating local coordinates, and positional animation is done in global coordinates. I made a new empty gameobject and called it “TextHolder”. Now why is this important?

Local coordinates are stated relative to a parent, and global coordinates are stated relative to the scene’s origin at (0,0,0). If we were to animate the position of our text, going from say, (0,0,0) to (0,4,0), these would be global coordinates. We wouldn’t be able to move the text away from these positions in global space, and our text would always spawn and move into the same positions, so instead we must force it to move upwards 4 units in local coordinates by making all coordinates relative to a parent gameobject. Reset the transforms of both objects to (0,0,0).

Animation

To open the animation tab, you can go to Window > Animation > Animation or hit Ctrl + 6 on the keyboard. With the Text (not the holder) selected, create a new animation and call it whatever you like. Then, we can add keyframes by autokeyframing (the red recording button) at 0:00s and 1:00s (a one second long animation). Just set the initial values at 0s for y position, scale and vertex colour, then set the final values at 1s (eg. Y position higher up, smaller font size, vertex colour as transparent)

How to Destroy Gameobject on Animation End

To destroy the gameobject when the animation is done, we have several options, but the easiest is with a hacky method with Animation Events. You can add one by going to the final frame and then hitting the bookmark looking icon. This allows us to call any public method attached to the gameobject being animated, and we can create a simple “self-deletion” script called “DeleteOnAnimEnd.cs” and attach this to the animated text gameobject. We also want to clean up the parent, so we will create a one line function that destroys the parent’s gameobject once called.

Points about Code:
  • gameObject, with a lowercase g, references the gameobject that the script is attached to.
  • Parents and children are properties of the transform component.
  • To get the transform component, or any component, we can use gameObject.GetComponent (), but some special components have shorthand for this, transform with a lowercase t will be shorthand for GetComponent() and returns a reference to the transform.
  • To get the parent, we can use the .parent variable, which returns the transform which is a parent to the current transform.
  • We can only destroy gameObjects, not transforms on their own, so to get the attached gameobject to the transform, we can use the .gameObject property of a transform.

If we set this as the function to be called at the animation event, (make sure to click the little bookmark in the timeline) we will have it trigger the DestroyParent() function at that frame, and thus destroy the parent (and child) gameobject.

Prefabbing

Prefabs in Unity are useful to create extensible, multipurpose and instantiable content. We can drag the textholder gameobject from the hierarchy into the project tab to create a prefab. Then, if we drag out the textholder prefab into the scene, we’ll see it is regenerated.

Enemy

Our enemy can be anything, it’s just a 2D sprite in this case that will have something spawn on top of it.

To imitate damage, well create a new script that detects when the player presses the X key on the keyboard, then instantiates the damage text over the enemy’s head with a customizable string. I called it GameManager.cs, and the code is below.

Points about Code
  • We need references to the prefab, enemy and a public (exposed) string to display. This should be set in the inspector to the correct values.
  • We must** import TMPro**, as seen on line 4, in order to manipulate textmeshpro objects
  • Instantiate() has several overloads, the one I’m using is (gameObject, parentTransform). The enemy is parent so the damage text will inherit its position, velocity, etc.
  • To manipulate our instantiated gameobject, we must place it in a variable. Instantiate() returns a reference to the instance.
  • To access the actual damage text, we must get the child of the prefab, which is obtained by .transform.GetChild(0), then we can get to the textmeshpro component which allows us to set the text to our custom string.

To activate this code, we’ll have to attach it to something in our scene. I suggest the main camera.

Then, play the scene and test it out! This is the end of the standard animation part of this tutorial.
Advanced: Animation from Code

For a more advanced and flexible technique, we can do everything from code, with means we can easily adjust the start and end colour, height, scale and other properties from code, rather than by adding new keyframes. The following code will permit you to do so, simply add this to a textmeshpro Text gameobject, and set the properties. No parenting is required. You can turn the gameobject, with this component, into a prefab and instantiate it the same way as above, but we can change the line

as we no longer need the child reference.

Procedural Code

We are taking advantage of the LERP function to smoothly transition from an initial to final state, controlled by a progress variable which is affected by the total time passed divided by the duration of the animation. As this is altogether more complex than the other techniques I explore, I will make a separate guide on this in the future. For now, I suggest you only use this code as a jumping off point, and I have no guarantees that it will work 🙂

Conclusion

While there are many esoteric ways of creating a hit indicator, damage text and crit marker in Unity, I think instantiating an animated TextMeshPro text is the easiest way, but it can be a bit inflexible so a procedural approach to circumvent the animation component can produce more desirable results, with more skill and effort applied.

TextMeshPro

com.unity.textmeshpro

Описание

TextMeshPro — это идеальное текстовое решение для Unity. Это идеальная замена текстовому интерфейсу Unity и устаревшей текстовой сетке.

Мощный и простой в использовании TextMeshPro (также известный как TMP) использует расширенные методы визуализации текста вместе с набором пользовательских шейдеров; обеспечивая существенное улучшение визуального качества, а также предоставляя пользователям невероятную гибкость, когда речь идет о стилизации текста и текстурировании.

TextMeshPro обеспечивает улучшенный контроль над форматированием и макетом текста с такими функциями, как интервалы между символами, словами, строками и абзацами, кернинг, выравнивание текста по ширине, ссылки, более 30 тегов форматированного текста, поддержка нескольких шрифтов и спрайтов, пользовательские стили и многое другое.

Отличная производительность. Поскольку геометрия, созданная TextMeshPro, использует два треугольника на символ, как и текстовые компоненты Unity, это улучшенное визуальное качество и гибкость не требуют дополнительных затрат на производительность.

How to write a Text Mesh Pro text from Script in Unity

In this arti­cle we will see how to work with the Text Mesh Pro com­po­nents from a Script, in addi­tion you will find a video from the chan­nel in which we will cre­ate a TEXT OBJECT to dis­play in a Can­vas and anoth­er Text Mesh for the 3D space and we will cre­ate a Script inside which we will mod­i­fy the text that these com­po­nents show, as an extra we will also mod­i­fy the col­or by code.

Text Mesh Pro has now become the stan­dard solu­tion for dis­play­ing text in Uni­ty, replac­ing the Text Mesh com­po­nent for dis­play­ing text in the 3D view and the Text com­po­nent for adding text in the UI. The old Text Mesh and Text com­po­nents can still be used, only that they are in a «Lega­cy» sec­tion, this is indi­cat­ing that it is prefer­able to use Text Mesh Pro and per­haps lat­er the old com­po­nents will no longer be available.

Fig.1: The Text com­po­nent has been moved to the «Lega­cy» section.

ABOUT THIS VIDEO

In this video we see how to SETUP TEXT MESH PRO in Uni­ty and how to write a Text Mesh Pro text in Uni­ty through code.

Dear read­er

In the chan­nel there lots of videos about Blender, Uni­ty and pro­gram­ming
in which we solve dif­fer­ent prob­lems and we pro­vide use­ful infor­ma­tion on these topics.

Creating Text Mesh Pro objects for World Space and Canvas

We start by cre­at­ing the Text objects that we will lat­er mod­i­fy from a Script, we are going to cre­ate two types of Text Mesh Pro objects, one to use in the user inter­face and anoth­er to use as a 3D object in the scene.

Creating Text Mesh Pro Text for the user interface

In Uni­ty the Text Mesh Pro objects that are in the UI sec­tion must be placed as chil­dren of a Can­vas object, so let’s assume that we already have one of these objects in the scene. To cre­ate a new Text Mesh Pro object we go to the hier­ar­chy, right click on the Can­vas (or any child object of the Can­vas), go to the UI sec­tion and choose the «Text — Text Mesh Pro» option, as shown in fig­ure 2.A.

Fig. 2.A: Option to cre­ate a new Text Mesh Pro text for the user interface.

Creation of Text Mesh Pro Text for World Space

The oth­er option to write text on the screen is to use a Text com­po­nent of Text Mesh Pro as a 3D object and there­fore locat­ed in a posi­tion in the world, this object will be found in the «3D Object» sec­tion of the cre­ation win­dow, as shown in fig­ure 2.B.

Fig. 2.B: Option to cre­ate a new Text Mesh Pro text as a 3D object in the scene.

MOST SEARCHED VIDEOS FROM MY CHANNEL

ABOUT UNITY

ABOUT BLENDER

First time using Text Mesh Pro

In case we have not con­fig­ured Text Mesh Pro yet, we will get the win­dow shown in fig­ure 3 where we will be giv­en the option to import the nec­es­sary com­po­nents to use Text Mesh Pro, we click on «Import TMP Essen­tials», as shown in fig­ure 3. The sec­ond but­ton to import exam­ples and extras is optional.

Fig­ure 3: Win­dow for import­ing Text Mesh Pro pack­age into Unity.

Result of the creation of objects

Once the objects were cre­at­ed, I made a few mod­i­fi­ca­tions in the inspec­tor (font size, text) and the result is as follows:

Fig. 4.a: Text Mesh Pro objects in the hierarchy.
Fig. 4.b: Text Mesh Pro objects dis­played in the scene.

Once the objects have been cre­at­ed and Text Mesh Pro import­ed we can start using the Text Mesh Pro Text com­po­nent from the inspec­tor or write it through a Script. In fig­ure 5 we see the Text com­po­nent in the Inspec­tor win­dow, it has many more con­fig­u­ra­tion options com­pared to the old text solution.

IMPORTANT

In fig­ure 5 we see the field to edit the text that appears on the screen, cur­rent­ly has writ­ten the val­ue «Can­vas Text», that is the field that we want to edit by code and to do it we will have to edit a vari­able called «text» that is define in that component.

Fig. 5: Text Mesh Pro com­po­nent in the inspector.

Script for writing text in Text Mesh Pro component

In order to write a Text Mesh Pro com­po­nent by code I will cre­ate a script and assign it to some GameOb­ject of the hier­ar­chy, as shown in fig­ure 6. In this case my script is called «Mod­i­fy­TextMesh­Pro», inside this script I will mod­i­fy the texts.

Fig. 6: We cre­ate a script and assign it to some object in the hierarchy.

Import TMPro namespace in our Script

To be able to use the Text Mesh Pro com­po­nents com­fort­ably, it is con­ve­nient to import the «TMPro» name­space by adding in the head­er of our script the line «using TMPro;» as shown in fig­ure 7.

Fig. 7: We declare that we are going to use the name­space «TMPro» in the head­er of our script.

Declaration of the variables to be used

We are going to declare two vari­ables of type «TMP_Text» where the ref­er­ences of the Text com­po­nents that we want to mod­i­fy will be stored, in this case the names of my vari­ables will be «can­vas­Text» and «world­Text», in these vari­ables I will place the Text Mesh Pro Text com­po­nents of the can­vas and the world space respectively.

DETAIL

The names «can­vas­Text» and «world­Text» are the names I chose for these vari­ables, you can use any oth­er name as long as it con­tains the allowed characters.

Fig. 8: Dec­la­ra­tion of the vari­ables to be used to mod­i­fy the Text Mesh Pro text.

Initialization of variables (Assignment of references)

The ini­tial­iza­tion of this type of non-prim­i­tive vari­ables is cru­cial, if we do not take care of putting inside the vari­able the pre­cise object we want to refer to, we will get a null ref­er­ence exception.

There are many ways to ini­tial­ize the vari­ables, in this case I will do it in one of the sim­plest ways which is by drag­ging the GameOb­jects that con­tain the Text com­po­nents I want to mod­i­fy to the vari­able spaces in the inspector.

Fig. 9: The appro­pri­ate GameOb­jects are dragged into the spaces in the inspec­tor to ini­tial­ize the variables.

The declared variable does not appear in the inspector

In the case that the vari­able does not appear in the inspec­tor it is usu­al­ly because its vis­i­bil­i­ty is pri­vate, it can be solved by declar­ing the vari­ables as pub­lic as shown in fig­ure 8, adding the word «pub­lic», or they can also be declared as pri­vate but indi­cat­ing that they are seri­al­ized by the inspec­tor, as follows:

[Seri­al­ize­Field]
TMP_Text can­vas­Text;

[Seri­al­ize­Field]
pri­vate TMP_Text canvasText;

Anoth­er rea­son why the vari­ables do not appear in the inspec­tor can be when there are errors in con­sole and the changes made in the scripts are not updat­ed, to solve this we will have to solve all the errors that there are in con­sole, once made this Uni­ty will com­pile and the new mod­i­fi­ca­tions will appear.

Code instructions for modifying Text Mesh Pro text via Script and tests

Once we have ini­tial­ized the vari­ables we can use them, in this case if we want to mod­i­fy the text dis­played by the Text Mesh Pro com­po­nent, we must mod­i­fy the vari­able «text» defined inside it, for this we use the dot oper­a­tor that allows us to access the vari­ables and pub­lic func­tions defined inside an object,

Fig. 10.A: Writ­ing a Text Mesh Pro text from a Script in Unity.
Fig. 10.B: Press­ing play shows how the texts on the screen are modified.

Extra: Change the color of a Text Mesh Pro text by code

Fig. 11.A: In lines 22 and 23 the col­or of the Text Mesh Pro texts is changed by code.
Fig. 11.B: When press­ing play we can see how the col­ors of the texts on the screen change.

Читать:
Как посмотреть когда было запущено приложение на windows 10

Похожие статьи