Search Unity

TextMesh Pro Extend TextMeshProUGUI with Play Mode undo "text"

Discussion in 'UGUI & TextMesh Pro' started by skwsk8, Feb 13, 2019.

  1. skwsk8

    skwsk8

    Joined:
    Jul 6, 2014
    Posts:
    35
    I've extended TextMeshProUGUI to make a CustomText class, but whenever the "text" property is set to a new value in code in Play Mode, the "text" is still changed in the asset when exiting Play Mode. I'd expect changes in Play Mode to not persist, but they are overwriting the actual asset.

    I imagine there's some sort of Undo that needs to occur, but I'm not sure how/why since it undo's fine when its a regular (non-extended) TextMeshProUGUI, and other UI extensions do not require additional undo code.

    Here's what the extension code looks like, including the usage:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using TMPro;
    4. using UnityEngine;
    5.  
    6. [DisallowMultipleComponent]
    7. [RequireComponent(typeof(RectTransform))]
    8. [RequireComponent(typeof(CanvasRenderer))]
    9. [AddComponentMenu("UI/CustomText", 2)]
    10. public class CustomText : TextMeshProUGUI {
    11.  
    12.     protected override void Start() {
    13.         base.Start();
    14.         SetLocalizedText("Some String");
    15.     }
    16.  
    17.     public void SetLocalizedText(string localizedString) {
    18.         //text is the property belongs to TMP_Text, which is a parent of TextMeshProUGUI
    19.         text = localizedString; //this is what needs to only effect the instance, not the source asset
    20.     }
    21.  
    22.     protected override void OnDestroy() {
    23.         //stuff
    24.         base.OnDestroy();
    25.     }
    26. }
    Note: I also made an editor extension that just extends TMP_UiEditorPanel and adds the one custom property needed.

    How do I get the extended TextMeshProUGUI class to either not overwrite the text asset in Play Mode, or if unavoidable, properly undo?
     
    Last edited: Feb 14, 2019
  2. skwsk8

    skwsk8

    Joined:
    Jul 6, 2014
    Posts:
    35
    Solved:

    UI components that are inherited have [ExecuteInEditMode] or [ExecuteAlways], which makes the Start() [Awake() too] run in editor when exiting Play Mode since Edit Mode starts, so the solution is:

    Code (CSharp):
    1.  
    2. protected override void Start() {
    3.         base.Start();
    4. #if UNITY_EDITOR
    5.         if(!UnityEditor.EditorApplication.isPlaying) {
    6.             return;
    7.         }
    8. #endif
    9.         SetLocalizedText("Some String");
    10. }
    11.