简体   繁体   中英

Unity how to Create Texts via script?

I'm trying to create Texts via script. I want to create texts with the name of objects of a certain tag.

"For example, if I have two objects named Cube and Sphere and both have a tag of "TargetObj" then their names should be displayed as texts on the screen(in the case Cube, Sphere)"

I want to achieve this regardless of the number of objects. so a loop is needed.

Here is what I've tried so far.

[SerializeField] GameObject LevelCanvas; 
       targetObjects = GameObject.FindGameObjectsWithTag("TargetObj");
            foreach (var obj in targetObjects)
            {
              
               Text mytext = LevelCanvas.AddComponent<Text>();
                 mytext.text = "Find " + obj.name;
                 Font ArialFont = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
                 mytext.font = ArialFont;
                 mytext.material = ArialFont.material;    
            }

it only shows one object name although I have 2 more objects that were supposed to be shown as well.

Many components in unity can only be added once per game object. That means you need a separate game object for every text you want to show. A typical way to approach this is to create a "prefab" of a game object which has a text element already. This way you can set a default font and other settings.

Then in code you use the Instantiate method on that prefab and via GetComponent() you can access the text component instance to set the desired string to display.

You need to create a text object on a new gameobject.

static Text CreateText(Transform parent)
{
    var go = new GameObject();
    go.transform.parent = parent;
    var text = go.AddComponent<Text>();
    return text;
}
var mytext = CreateText(LevelCanvas.transform);
myext.text = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM