Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

c# - When trying to fetch all the ui texts from all the scene I'm getting error in the array. How could I solve it?

I have two scenes Game and Main Menu. and both scene are in the hierarchy. Both scenes have ui elements also text ui elements.

The script is attached to a gameobject in the Game scene :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class BackToMainMenu : MonoBehaviour
{
    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;
            }
        }
    }

    [ContextMenu("Fetch Ui Texts")]
    private void FetchAllTexts()
    {
        var tmp = new List<Text>();
        for (var i = 0; i < SceneManager.sceneCount; i++)
        {
            foreach (var root in SceneManager.GetSceneAt(i).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;
            }
        }
    }
}

When I click and make "Fetch Ui Texts" the result is :

Fetch error

The first 3 items are from the Game scene the rest items with the error inside are from the Main Menu scene.

When I click on the items with the error it's showing the item in the hierarchy in the main menu for example :

Item with error

Why this errors happens and how should I fix them ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...