Skip to content

Instantly share code, notes, and snippets.

@tklee1975
Created April 15, 2019 19:02
Show Gist options
  • Select an option

  • Save tklee1975/953dc33497e4e06e7957db06318bf031 to your computer and use it in GitHub Desktop.

Select an option

Save tklee1975/953dc33497e4e06e7957db06318bf031 to your computer and use it in GitHub Desktop.
Unity UI Tip - Text Style Setting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
[RequireComponent(typeof(Text))]
public class TextStyle : MonoBehaviour
{
[SerializeField] protected TextStyleSetting.Style m_style;
void UpdateTextWithStyle() {
if(TextStyleSetting.setting == null) {
Debug.LogWarning("TextStyle: cannot load the text setting");
return;
}
Text text = GetComponent<Text>();
if(text == null) {
Debug.LogWarning("TextStyle: no text component");
return;
}
TextStyleSetting.Setting setting = TextStyleSetting.setting.GetSetting(m_style);
if(setting.fontSize > 0) {
text.fontSize = setting.fontSize;
}
if(setting.fontType != null) {
text.font = setting.fontType;
}
}
void OnValidate()
{
//Debug.Log("TextStyle.OnValidate: is called");
UpdateTextWithStyle();
}
// Start is called before the first frame update
void Start()
{
UpdateTextWithStyle();
}
// Update is called once per frame
void Update()
{
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
// note: 1. Create the Scriptable Object
// 2. Set font and font size for each style
// 3. Move it to Resources folder
[CreateAssetMenu(fileName = "TextStyleSetting", menuName = "TextStyle/Setting", order = 1)]
public class TextStyleSetting : ScriptableObject {
[System.Serializable]
public struct Setting {
[Range(1, 50)] public int fontSize;
public Font fontType;
public override string ToString() {
return "fontSize=" + fontSize + " fontType=" + fontType;
}
}
public enum Style {
Title,
Heading1,
Heading2,
Heading3,
Body,
}
public Setting title;
public Setting heading1;
public Setting heading2;
public Setting heading3;
public Setting body;
public Setting GetSetting(Style style) {
if(Style.Title == style) {
return title;
} else if(Style.Heading1 == style) {
return heading1;
} else if(Style.Heading2 == style) {
return heading2;
} else if(Style.Heading3 == style) {
return heading3;
} else {
return body;
}
}
public string Info() {
string info = "";
info += "title=" + title.ToString();
return info;
}
private static TextStyleSetting s_setting = null;
public static TextStyleSetting setting {
get {
if(s_setting == null) {
s_setting = Resources.Load<TextStyleSetting>("TextStyleSetting");
}
return s_setting;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment