Good evening.
I’ve written a C# script that is supposed to create a UI text object at runtime the same way it would be achieved from the editor.
It does work and there are no errors, but it’s fairly clunky in my opinion. I was wondering if anyone might be able to assist me in condensing it to any beneficial degree. Is there a more concise way to attain this functionality?
I did note that some of these values are the same as the default values that would be used if I neglected to address them, but leaving them out seems like asking for trouble.
Below I’ve rewritten an example of the script in question. Perhaps you can see that the code is (needlessly?) drawn out. Should I ever need to change the names of the variables, it would prove quite tedious (especially if I used such tactics to create several objects of similar or greater complexity).
Thank you in advance for any assistance provided.
Have a pleasant night.C# Code
{
private GameObject textObject;
private Text myText;
private RectTransform rTrans;
private Font font;
private string message;
void Start ()
{
font = Resources.FindObjectsOfTypeAll(typeof(Font))[0] as Font;
textObject = new GameObject("Text");
textObject.transform.SetParent(this.transform);
textObject.layer = 5;
myText = textObject.AddComponent<Text>();
rTrans = myText.rectTransform;
rTrans.localPosition = new Vector3(0, -48, 0);
rTrans. sizeDelta = new Vector2(480, 48);
rTrans.anchorMin = new Vector2(1, 1);
rTrans.anchorMax = new Vector2(1, 1);
rTrans.pivot = new Vector2(1, 1);
rTrans.localRotation = Quaternion.identity;
rTrans.localScale = new Vector3(1, 1, 1);
myText.font = font;
myText.text = message;
myText.fontStyle = FontStyle.Bold;
myText.fontSize = 18;
myText.lineSpacing = 1;
myText.supportRichText = false;
myText.alignment = TextAnchor.MiddleCenter;
myText.alignByGeometry = false;
myText.horizontalOverflow = HorizontalWrapMode.Wrap;
myText.verticalOverflow = VerticalWrapMode.Truncate;
myText.resizeTextForBestFit = false;
myText.color = new Color(255, 255, 255, 1);
myText.raycastTarget = false;
}
}