GameObject.Find()能否查找隐藏属性的游戏对象?

本文探讨了Unity中GameObject.Find()方法的限制,特别是对于acive=false的游戏对象的查找问题。介绍了如何通过设置SetActive属性来解决此问题,并概述了其他几种获取游戏对象的方法,如FindGameObjectsWithTag、FindObjectOfType等,及其在游戏开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GameObject.Find()能否查找隐藏属性的游戏对象

  1. GameObject.Find()
    通过场景里面的名子或者一个路径直接获取游戏对象。
    GameObject root = GameObject.Find(“GameObject”);

GameObject.Find()使用起来很方便,但是它有个缺陷,就是如果你的这个GameObject天生acive = false的话。那么你用GameObject.Find()是永远也无法获取它的对象的。如果对象都获取不到,那么对象身上脚本啊,组件啊啥的都是获取不到的,变成了没有意义的对象。
GameObject.Find()方法在游戏中的使用频率很高。但是它也很消耗性能。尤其是在Update方法中不要去 Find()游戏对象!

  1. 如果将物体天生的属性为false,物体就无法再继续使用,更不要提再设置为true
    但是如果想设置,就必须先将物体的SetActive设置为True,可以Awake()方法中将SetActive属性先设置为false,这样开始运行时物体的属性就为false(看做物体不存在),等再需要显示的时候,直接将物体的SetActive属性设置为true即可。这样就避免了天生属性为false的物体无法设置为true。

GameObject root = GameObject.Find(“root”);
root.SetActive(true); // 根节点不为空
root.transform.Find(“root/AnyChildObjectName”);

 3. **unity 还提供了几个获取游戏对象的方法**

GameObject.FindGameObjectsWithTag(“tag”)
GameObject.FindWithTag(“tag”)

根据一个标记来获取游戏对象,返回一个 或者 一个数组,我个人觉得这个两个方法没啥用,因为既然需要用到标记那么相比这个游戏对象必然是非常特殊的一个,所以我会把它存在内存中。

Object.FindObjectOfType
Object.FindObjectsOfType
Resources.FindObjectsOfTypeAll 

根据一个类型返回Object,比如 GameObject 、Texture、Animation 、甚至还可以是你自己写的一个脚本 的范型。它找起来很方便,可以返回一个 或者一个数组。 我觉得这几个方法其实游戏中也没啥用,不过在编辑器中使用的确实很频繁,比如你要做批量检查场景的工具,查找场景中有没有使用某个特殊类型的对象。 或者查看内存的占用量,看看当前内存中那些Texture没有被释放掉。 等等。

using System.Collections.Generic; using UnityEngine; using TMPro; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine.EventSystems; public class DialogueManager : MonoBehaviour { public enum DialogueState { Before, Win, Lost } public static DialogueManager Instance; [Header("UI Elements")] public TextMeshProUGUI tmpText; public float typingSpeed = 0.05f; public TMP_FontAsset fallbackFont; // 备用字体 [Header("Dialogue Content")] public List<string> beforeBattleDialogues = new List<string>(); public List<string> winDialogues = new List<string>(); public List<string> lostDialogues = new List<string>(); [Header("场景布置")] public GameObject image; public GameObject image1; public GameObject image2; public TextMeshProUGUI text; [Header("按钮设置")] public Button startButton; public Button loseButton; public Button winButton; [Header("UI 元素路径")] public string tmpTextPath = "Canvas/DialoguePanel/TMPText"; public string startButtonPath = "Canvas/Buttons/StartButton"; public string winButtonPath = "Canvas/Buttons/WinButton"; public string loseButtonPath = "Canvas/Buttons/LoseButton"; public string imagePath = "Canvas/Background"; private bool isTyping = false; private Coroutine typingCoroutine; private string currentSentence; public DialogueState currentState = DialogueState.Before; public int currentDialogueIndex = 0; private List<string> currentDialogueList; private TextMeshProUGUI _currentTmpText; private Button _currentStartButton; private Button _currentWinButton; private Button _currentLoseButton; private GameObject _currentImage; void Awake() { // 单例模式实现 if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); SceneManager.sceneLoaded += OnSceneLoaded; Debug.Log("对话管理器初始化完成"); } else { Destroy(gameObject); return; } } void Start() { // 初始状态加载 LoadInitialState(); } void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; } private void LoadInitialState() { // 确保对话列表初始化 InitializeDialogueLists(); Debug.Log("加载初始对话状态..."); // 检查存档中的对话状态 if (SaveSystem.Instance != null && SaveSystem.Instance.SaveExists()) { DialogueState savedState = SaveSystem.Instance.GetDialogueState(); int savedIndex = SaveSystem.Instance.GetDialogueIndex(); // 使用SetDialogueState确保正确初始化 SetDialogueState(savedState); currentDialogueIndex = savedIndex; Debug.Log($"从存档加载对话状态: {savedState} 索引: {savedIndex}"); } else { // 检查战斗结果 int result = PlayerPrefs.GetInt("LastBattleResult", -1); // 使用状态设置方法确保列表初始化 if (result == 1) SetDialogueState(DialogueState.Win); else if (result == 0) SetDialogueState(DialogueState.Lost); else SetDialogueState(DialogueState.Before); } // 清除状态 PlayerPrefs.DeleteKey("LastBattleResult"); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { // 仅初始化UI但不启动对话 StartCoroutine(InitializeUIWithoutDialogue()); } private IEnumerator InitializeUIWithoutDialogue() { yield return null; Debug.Log("初始化UI组件但不启动对话..."); // 仅执行UI初始化逻辑 // 不包含StartStateDialogue()调用 } private IEnumerator ReinitializeUIAfterFrame() { yield return null; // 等待一帧确保场景完全加载 Debug.Log("重新初始化UI组件..."); // 1. 重新获取当前场景的UI引用 _currentTmpText = GameObject.Find(tmpTextPath)?.GetComponent<TextMeshProUGUI>(); _currentStartButton = GameObject.Find(startButtonPath)?.GetComponent<Button>(); _currentWinButton = GameObject.Find(winButtonPath)?.GetComponent<Button>(); _currentLoseButton = GameObject.Find(loseButtonPath)?.GetComponent<Button>(); _currentImage = GameObject.Find(imagePath); // 2. 更新公共引用 if (_currentTmpText != null) { tmpText = _currentTmpText; EnsureFontLoaded(); // 确保字体加载 } if (_currentStartButton != null) startButton = _currentStartButton; if (_currentWinButton != null) winButton = _currentWinButton; if (_currentLoseButton != null) loseButton = _currentLoseButton; if (_currentImage != null) image = _currentImage; // 3. 重新绑定按钮事件 if (startButton != null) { startButton.onClick.RemoveAllListeners(); startButton.onClick.AddListener(OnStartClick); startButton.gameObject.SetActive(false); } if (loseButton != null) { loseButton.onClick.RemoveAllListeners(); loseButton.onClick.AddListener(OnLoseClick); loseButton.gameObject.SetActive(false); } if (winButton != null) { winButton.onClick.RemoveAllListeners(); winButton.onClick.AddListener(OnWinClick); winButton.gameObject.SetActive(false); } // 4. 确保事件系统存在 EnsureEventSystemExists(); // 5. 恢复UI状态 if (tmpText != null) { tmpText.gameObject.SetActive(false); } // 6. 继续之前的对话状态 StartStateDialogue(); } // 确保字体加载 private void EnsureFontLoaded() { if (tmpText == null) return; // 如果主字体丢失,使用备用字体 if (tmpText.font == null || tmpText.font.name == "Fallback") { if (fallbackFont != null) { tmpText.font = fallbackFont; Debug.Log("使用备用字体"); } else { Debug.LogError("主字体和备用字体均不可用!"); } } // 确保材质正确 if (tmpText.fontSharedMaterial == null) { Debug.LogWarning("字体材质丢失,使用默认材质"); tmpText.fontSharedMaterial = fallbackFont.material; } } void Update() { if (tmpText == null) { Debug.LogWarning("tmpText引用为空!"); return; } // 添加跳过功能:按E键跳过当前打字效果 if (Input.GetKeyDown(KeyCode.E) && isTyping) { SkipTyping(); } // 按E键继续下一句对话 else if (Input.GetKeyDown(KeyCode.E) && !isTyping && tmpText.gameObject.activeSelf) { NextSentence(); } } // 设置当前对话状态 public void SetDialogueState(DialogueState newState) { currentState = newState; currentDialogueIndex = 0; switch (newState) { case DialogueState.Before: currentDialogueList = beforeBattleDialogues; break; case DialogueState.Win: currentDialogueList = winDialogues; break; case DialogueState.Lost: currentDialogueList = lostDialogues; break; } Debug.Log($"状态已切换至: {newState}"); // 保存状态 SaveDialogueState(); } // 保存对话状态 private void SaveDialogueState() { if (SaveSystem.Instance != null) { SaveSystem.Instance.SaveDialogueState(currentState, currentDialogueIndex); } } private void InitializeDialogueLists() { // 确保所有对话列表都已初始化 if (beforeBattleDialogues == null) beforeBattleDialogues = new List<string>(); if (winDialogues == null) winDialogues = new List<string>(); if (lostDialogues == null) lostDialogues = new List<string>(); // 添加默认对话防止空列表 if (beforeBattleDialogues.Count == 0) beforeBattleDialogues.Add("默认对话:请添加战斗前对话内容"); if (winDialogues.Count == 0) winDialogues.Add("默认对话:请添加胜利后对话内容"); if (lostDialogues.Count == 0) lostDialogues.Add("默认对话:请添加失败后对话内容"); } // 启动当前状态的对话 public void StartStateDialogue() { if (currentDialogueList == null || currentDialogueList.Count == 0) { Debug.LogWarning($"当前对话列表为空! 状态: {currentState}"); // 自动恢复默认列表 SetDialogueState(currentState); } // 确保索引在有效范围内 currentDialogueIndex = Mathf.Clamp(currentDialogueIndex, 0, currentDialogueList.Count - 1); currentSentence = currentDialogueList[currentDialogueIndex]; Debug.Log($"开始对话: {currentSentence}"); // 暂停玩家移动 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = false; // 锁定玩家输入 Cursor.lockState = CursorLockMode.None; Cursor.visible = true; // 显示对话框UI tmpText.gameObject.SetActive(true); BringDialogueToFront(); // 确保在最前层 // 启动打字效果协程 if (isTyping) { StopCoroutine(typingCoroutine); } typingCoroutine = StartCoroutine(TypeSentence(currentSentence)); } // 确保对话框在最前层 private void BringDialogueToFront() { if (tmpText != null) { tmpText.transform.SetAsLastSibling(); Canvas canvas = tmpText.GetComponentInParent<Canvas>(); if (canvas != null) { canvas.sortingOrder = 100; // 设为最高层级 Debug.Log($"设置Canvas层级: {canvas.sortingOrder}"); } } } // 显示下一句对话 public void NextSentence() { currentDialogueIndex++; if (currentDialogueIndex < currentDialogueList.Count) { StartStateDialogue(); // 保存当前进度 SaveDialogueState(); } else { // 对话结束 EndDialogue(); } } IEnumerator TypeSentence(string sentence) { isTyping = true; tmpText.text = ""; // 确保文本颜色可见 tmpText.color = new Color(tmpText.color.r, tmpText.color.g, tmpText.color.b, 1f); // 逐字显示 foreach (char letter in sentence.ToCharArray()) { tmpText.text += letter; yield return new WaitForSeconds(typingSpeed); } isTyping = false; } // 跳过当前打字效果 public void SkipTyping() { if (isTyping && typingCoroutine != null) { StopCoroutine(typingCoroutine); tmpText.text = currentSentence; isTyping = false; } } public void EndDialogue() { Debug.Log("对话结束"); if (isTyping && typingCoroutine != null) { StopCoroutine(typingCoroutine); isTyping = false; } // 恢复玩家控制 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; // 隐藏对话框 if (tmpText != null) { tmpText.gameObject.SetActive(false); } // 根据状态显示对应按钮 switch (currentState) { case DialogueState.Before: if (startButton != null) { startButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(startButton.gameObject); } break; case DialogueState.Win: if (winButton != null) { winButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(winButton.gameObject); } break; case DialogueState.Lost: if (loseButton != null) { loseButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(loseButton.gameObject); } break; } // 确保事件系统可用 EnsureEventSystemExists(); // 保存完成状态 SaveDialogueState(); } private void EnsureEventSystemExists() { EventSystem eventSystem = FindObjectOfType<EventSystem>(); if (eventSystem == null) { GameObject eventSystemObj = new GameObject("EventSystem"); eventSystem = eventSystemObj.AddComponent<EventSystem>(); eventSystemObj.AddComponent<StandaloneInputModule>(); Debug.Log("创建新事件系统"); } else if (eventSystem.GetComponent<StandaloneInputModule>() == null) { eventSystem.gameObject.AddComponent<StandaloneInputModule>(); Debug.Log("添加输入模块到事件系统"); } } public void OnMainMenuClick() { Debug.Log("主菜单按钮点击"); SceneManager.LoadScene("MainMenu"); } public void OnStartClick() { Debug.Log("开始作战"); SceneManager.LoadScene("Fight"); } public void OnLoseClick() { Debug.Log("失败按钮点击"); SceneManager.LoadScene("Fight"); } public void OnWinClick() { if (currentState != DialogueState.Win) { Debug.LogWarning("尝试在非胜利状态执行胜利逻辑"); return; } playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; Debug.Log("执行胜利逻辑"); if (image != null) image.SetActive(false); if (image1 != null) image1.SetActive(false); if (image2 != null) image2.SetActive(false); if (text != null) text.gameObject.SetActive(false); if (tmpText != null) tmpText.gameObject.SetActive(false); if (winButton != null) winButton.gameObject.SetActive(false); // 清除对话存档 if (SaveSystem.Instance != null) { SaveSystem.Instance.SaveDialogueState(DialogueState.Before, 0); } } } 我怀疑是装换sence之后导致检测不到之前的组件
最新发布
08-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值