0
\$\begingroup\$

When pausing/resuming the game, I want to disable/enable all UI texts.

The following code works for finding UI texts, but I also want it to find TextMesh Pro text.

How can I do this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
     
public class BackToMainMenu : MonoBehaviour
{
    [ContextMenuItem("Fetch", nameof(FetchAllTexts))]
    public Text[] uiTexts;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                SceneManager.UnloadSceneAsync(0);
                DisableEnableUiTexts(false);
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                DisableEnableUiTexts(true);
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                Cursor.visible = true;
            }
        }
    }

    private void FetchAllTexts()
    {
        var tmp = new List<Text>();
        foreach (var root in SceneManager.GetSceneAt(0).GetRootGameObjects())
        {
            tmp.AddRange(root.GetComponentsInChildren<Text>(true));
        }
        Text[] texts = tmp.ToArray();

        uiTexts = texts;
    }

    private void DisableEnableUiTexts(bool uiTextEnabled)
    {
        if (uiTexts.Length > 0)
        {
            foreach (Text ui in uiTexts)
            {
                ui.enabled = uiTextEnabled;
            }
        }
    }
}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

According to your comment you are using as well TextMeshPro. You are already iterating over all elements in the root loop. You might want to have a second list for all TextMeshPro elements to not always cast between them.

 var textMeshProList = new List<TextMeshProUGUI>();
 foreach (var root in SceneManager.GetSceneAt(0).GetRootGameObjects())
 {
    tmp.AddRange(root.GetComponentsInChildren<Text>(true));
    textMeshProList.AddRange(root.GetComponentsInChildren<TextMeshProUGUI>(true));
 }

There are two different TextMeshPro Ui Text elements

  • TextMeshProUGUI
  • TextMeshPro

Depending which one you used you need to change the type. Or add both if you used both.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .