1.Extensionをセット
using UnityEngine;
public static class GameObjectUtils
{
public static GameObject Clone(this GameObject go,string newname=null)
{
var clone = GameObject.Instantiate( go ) as GameObject;
clone.transform.parent = go.transform.parent;
clone.transform.localPosition = go.transform.localPosition;
clone.transform.localScale = go.transform.localScale;
if(newname!=null) clone.name=newname;
return clone;
}
}
public static class ColorStringExtension
{
public static Color ToColor(this string self)
{
var color = default(Color);
ColorUtility.TryParseHtmlString(self, out color);
return color;
}
}
2.UI.Text
を適当に作成。いい感じに設計。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class baseText : MonoBehaviour
{
[SerializeField]Text m_text;
void Awake(){
gameObject.name="BaseText";//
gameObject.transform.localPosition=Vector3.zero;
m_text=gameObject.GetComponent<Text>();
m_text.fontSize=16;
m_text.color="#0f0".ToColor();
}
public void SetText(float x,float y,string text){
m_text.text =text;
gameObject.transform.localPosition = new Vector3(x,y,0);
}
public void SetText(string text)=>m_text.text=text;
}
3.使い回す。Canvasの直下あたりで
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class texttest : MonoBehaviour
{
// Start is called before the first frame update
GameObject a;
GameObject b;
void Start()
{
a=GameObject.Find("BaseText").Clone("test1");
a.GetComponent<baseText>().SetText("test1");
//
b=GameObject.Find("BaseText").Clone("test2");
b.GetComponent<baseText>().SetText(0,16,"test2222222");
}
// Update is called once per frame
void Update()
{
if(Input.anyKey){
GameObject.Destroy(a);
GameObject.Destroy(b);
}
}
}