- Home /
trouble instantiating ui text
I'm trying to instantiate a text ui so that it appears a bit above the original
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChatDialogue : MonoBehaviour
{
public GameObject chatParent;
public GameObject chatText;
public Vector2 chatPos;
void Start()
{
chatPos = new Vector2(-413, -320 + 60);
Quaternion rotation = Quaternion.Euler(0,0,0);
Instantiate(chatText, chatPos, rotation);
//currentTXT.transform.parent = chatParent.transform;
}
void Update()
{
}
}
The problem I was having was that the instantiated text was not appearing on the screen. I looked at posts with the same problem and apparently I had to make the instantiated texts a child of the canvas on the hierarchy which I tried to do (the commented out line). When I run it however, it starts making infinite clones in the hierarchy which freezes unity. This happens with or without the last line in the Start void. Below is what I attached the script to and where it is in the hierarchy
Answer by olejuer · Jul 04, 2020 at 09:05 AM
Your issue is a recursion. The ChatDialogue will spawn another ChatDialogue in its Start() method. This, in turn, well then spawn another and so on. You will end up creating a ChatDialogue every frame.
chatText should be a reference to a prefab that does not have this script attached.
As for the positioning, you probably want to set the parent to the canvas and then adjust the local position of your new instance, not the global position. I do not know how to position UI elements with code by heart, so I cannot give you any sample code. Try to put your object where you want it with the editor and then look at the state in the inspector. The transform value you see are local coordinates.
By the way, do you know about TextMeshPro? It is an alternative Text system which is integrated into Unity. It looks more complex at first, but will give you much better results. It renders vector graphics text instead of pixel graphics and is much more powerful in general.
Thanks, I didn't think about the scripts also duplicating but now everything works as intended. Also I did see Text$$anonymous$$eshPro before but didn't know what it was, I'm using it now though and it is much better, I appreciate the suggestion
Your answer
![](https://koobas.hobune.stream/wayback/20220613002436im_/https://answers.unity.com/themes/thub/images/avi.jpg)