Unity3d 不使用GameObject.SetActive,而是将GameObject移除到屏幕外

本文介绍了一个Unity扩展函数,用于将GameObject移除到屏幕外或还原其位置。提供了两种方法,一种基于本地坐标,另一种基于世界坐标。通过简单的示例代码展示了如何实现这一功能。

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

原创,转载请注明出处。

刘帅 2017年7月27日 第一次编写。

 

我简单尝试了一下编写了两个扩展函数,将指定GameObject移除屏幕外,使用方法与GameObject.SetActive(bool value)相同。

写了改变本地坐标和世界坐标两种方法,简单测试下来可行,两种方法效果相同:

public static class UnityExtension
{
    public static readonly Dictionary<int, Vector3> DicActiveLocalPosition = new Dictionary<int, Vector3>();
    public static void SetNewActiveLocal(this GameObject go, bool value)
    {
        if (!go)
        {
            return;
        }

        if (!value && go.transform.localPosition == Vector3.one * 100000)
        {
            return;
        }

        int id = go.GetInstanceID();
        if (go.transform.localPosition != Vector3.one * 100000)
        {
            DicActiveLocalPosition[id] = go.transform.localPosition;
        }

        Vector3 originLocalPosition = Vector3.zero;
        DicActiveLocalPosition.TryGetValue(id, out originLocalPosition);
        go.transform.localPosition = value ? originLocalPosition : Vector3.one * 100000;
    }



    public static readonly Dictionary<int, Vector3> DicActiveWorldPosition = new Dictionary<int, Vector3>();
    public static void SetNewActiveWorld(this GameObject go, bool value)
    {
        if (!go)
        {
            return;
        }

        if (!value && go.transform.position == Vector3.one * 100000)
        {
            return;
        }

        int id = go.GetInstanceID();
        if (go.transform.position != Vector3.one * 100000)
        {
            DicActiveWorldPosition[id] = go.transform.position;
        }

        Vector3 originWorldPosition = Vector3.zero;
        DicActiveWorldPosition.TryGetValue(id, out originWorldPosition);
        go.transform.position = value ? originWorldPosition : Vector3.one * 100000;
    }
}

 

using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; public class DialogueSystem : MonoBehaviour { public static DialogueSystem Instance { get; private set; } public Text nameText; public Text dialogueText; public Button continueButton; public Image avatarImage; public Button[] optionButtons; public GameObject optionsPanel; private string[] currentMessages; private int messageIndex; private List<DialogueOption> currentOptions; void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); gameObject.SetActive(false); continueButton.onClick.AddListener(ShowNextMessage); } public void ShowDialogue(string speaker, string[] messages, string avatarPath, List<DialogueOption> options = null) { gameObject.SetActive(true); nameText.text = speaker; if (!string.IsNullOrEmpty(avatarPath)) { Sprite avatarSprite = Resources.Load<Sprite>(avatarPath); if (avatarSprite != null) { avatarImage.sprite = avatarSprite; } else { Debug.LogWarning($"头像未找到: {avatarPath}"); avatarImage.gameObject.SetActive(false); } } currentMessages = messages; messageIndex = 0; currentOptions = options; continueButton.gameObject.SetActive(true); optionsPanel.SetActive(false); ShowNextMessage(); } private void ShowNextMessage() { optionsPanel.SetActive(false); if (messageIndex < currentMessages.Length) { dialogueText.text = currentMessages[messageIndex++]; continueButton.gameObject.SetActive(true); } else ShowOptions(); } private void ShowOptions() { if (currentOptions == null || currentOptions.Count == 0) { gameObject.SetActive(false); return; } continueButton.gameObject.SetActive(false); optionsPanel.SetActive(true); for (int i = 0; i < optionButtons.Length; i++) { bool hasOption = i < currentOptions.Count; optionButtons[i].gameObject.SetActive(hasOption); if (hasOption) { DialogueOption option = currentOptions[i]; optionButtons[i].GetComponentInChildren<Text>().text = option.text; optionButtons[i].onClick.RemoveAllListeners(); optionButtons[i].onClick.AddListener(() => SelectOption(option)); } } } private void SelectOption(DialogueOption option) { option.action?.Invoke(); gameObject.SetActive(false); } [System.Serializable] public class DialogueOption { public string text; public UnityEvent action; } } 为什么DontDestroyOnLoad没有出现
最新发布
08-16
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; [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 mainMenuButton; public Button startButton; public Button loseButton; public Button winButton; private bool isTyping = false; private Coroutine typingCoroutine; private string currentSentence; private DialogueState currentState = DialogueState.Before; private int currentDialogueIndex = 0; private List<string> currentDialogueList; void Start() { // 隐藏所有按钮 // 检查战斗结果 int result = PlayerPrefs.GetInt("LastBattleResult", -1); if (result == 1) { Debug.Log("战斗胜利 - 触发胜利对话"); SetDialogueState(DialogueState.Win); } else if (result == 0) { Debug.Log("战斗失败 - 触发失败对话"); SetDialogueState(DialogueState.Lost); } else { Debug.Log("首次进入 - 默认对话"); SetDialogueState(DialogueState.Before); } // 清除状态 PlayerPrefs.DeleteKey("LastBattleResult"); } void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); } // 初始化当前对话列表 currentDialogueList = beforeBattleDialogues; // 设置按钮点击事件 mainMenuButton?.onClick.RemoveAllListeners(); startButton?.onClick.RemoveAllListeners(); loseButton?.onClick.RemoveAllListeners(); winButton?.onClick.RemoveAllListeners(); // 重新绑定正确的事件 if (mainMenuButton != null) mainMenuButton.onClick.AddListener(OnMainMenuClick); if (startButton != null) startButton.onClick.AddListener(OnStartClick); if (loseButton != null) loseButton.onClick.AddListener(OnLoseClick); if (winButton != null) winButton.onClick.AddListener(OnWinClick); } void Update() { // 添加跳过功能:按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}"); } // 启动当前状态的对话 public void StartStateDialogue() { if (currentDialogueList == null || currentDialogueList.Count == 0) return; // 如果正在显示其他文本,先停止 if (isTyping) { StopCoroutine(typingCoroutine); } // 确保索引在有效范围内 currentDialogueIndex = Mathf.Clamp(currentDialogueIndex, 0, currentDialogueList.Count - 1); currentSentence = currentDialogueList[currentDialogueIndex]; // 暂停玩家移动 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = false; // 锁定玩家输入 Cursor.lockState = CursorLockMode.None; Cursor.visible = true; // 显示对话框UI tmpText.gameObject.SetActive(true); // 启动打字效果协程 typingCoroutine = StartCoroutine(TypeSentence(currentSentence)); } // 显示下一句对话 public void NextSentence() { currentDialogueIndex++; if (currentDialogueIndex < currentDialogueList.Count) { StartStateDialogue(); } else { // 对话结束 EndDialogue(); } } IEnumerator TypeSentence(string sentence) { isTyping = true; tmpText.text = ""; // 逐字显示 foreach (char letter in sentence.ToCharArray()) { tmpText.text += letter; yield return new WaitForSeconds(typingSpeed); } isTyping = false; } // 跳过当前打字效果 public void SkipTyping() { if (isTyping) { StopCoroutine(typingCoroutine); tmpText.text = currentSentence; isTyping = false; } } public void EndDialogue() { if (isTyping) { StopCoroutine(typingCoroutine); isTyping = false; } // 恢复玩家控制 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; // 隐藏对话框 tmpText.gameObject.SetActive(false); // 根据状态显示对应按钮 switch (currentState) { case DialogueState.Before: if (startButton != null) startButton.gameObject.SetActive(true); if (mainMenuButton != null) mainMenuButton.gameObject.SetActive(true); break; case DialogueState.Win: if (winButton != null) winButton.gameObject.SetActive(true); if (mainMenuButton != null) mainMenuButton.gameObject.SetActive(true); break; case DialogueState.Lost: if (loseButton != null) loseButton.gameObject.SetActive(true); if (mainMenuButton != null) mainMenuButton.gameObject.SetActive(true); break; } // 确保事件系统可用 EnsureEventSystemExists(); // 设置按钮为选中状态 if (currentState == DialogueState.Before && startButton != null) { EventSystem.current.SetSelectedGameObject(startButton.gameObject); } else if (currentState == DialogueState.Win && winButton != null) { EventSystem.current.SetSelectedGameObject(winButton.gameObject); } else if (currentState == DialogueState.Lost && loseButton != null) { EventSystem.current.SetSelectedGameObject(loseButton.gameObject); } } private void EnsureEventSystemExists() { EventSystem eventSystem = FindObjectOfType<EventSystem>(); if (eventSystem == null) { GameObject eventSystemObj = new GameObject("EventSystem"); eventSystem = eventSystemObj.AddComponent<EventSystem>(); eventSystemObj.AddComponent<StandaloneInputModule>(); } else if (eventSystem.GetComponent<StandaloneInputModule>() == null) { eventSystem.gameObject.AddComponent<StandaloneInputModule>(); } } private void OnMainMenuClick() { Debug.Log("主菜单按钮点击"); SceneManager.LoadScene("MainMenu"); } private void OnStartClick() { Debug.Log("开始作战"); SceneManager.LoadScene("Fight"); } private void OnLoseClick() { Debug.Log("失败按钮点击"); SceneManager.LoadScene("Fight"); } private void OnWinClick() { if (currentState != DialogueState.Win) { Debug.LogWarning("尝试在非胜利状态执行胜利逻辑"); return; } playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; Debug.Log("执行胜利逻辑"); image.SetActive(false); image1.SetActive(false); image2.SetActive(false); text.gameObject.SetActive(false); } }using TMPro; using UnityEngine; using UnityEngine.UI; public class NPC2 : MonoBehaviour { public GameObject image; public GameObject image1; public GameObject image2; public TextMeshProUGUI text; [Header("按钮设置")] public Button mainMenuButton; public Button startButton; public Button loseButton; public Button winButton; void Start() { // 将按钮引用传递给DialogueManager if (DialogueManager.Instance != null) { DialogueManager.Instance.mainMenuButton = mainMenuButton; DialogueManager.Instance.startButton = startButton; DialogueManager.Instance.loseButton = loseButton; DialogueManager.Instance.winButton = winButton; } // 初始化时隐藏所有按钮 if (mainMenuButton != null) mainMenuButton.gameObject.SetActive(false); if (startButton != null) startButton.gameObject.SetActive(false); if (loseButton != null) loseButton.gameObject.SetActive(false); if (winButton != null) winButton.gameObject.SetActive(false); } void OnTriggerStay2D(Collider2D other) { if (other.CompareTag("Player") && Input.GetKeyDown(KeyCode.F)) { image.SetActive(true); image1.SetActive(true); image2.SetActive(true); text.gameObject.SetActive(true); DialogueManager.Instance.StartStateDialogue(); } } }NPC2脚本结合Dialoguemanager脚本来讲同状态下button的出现放在触发器中
08-02
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(); StartCoroutine(ReinitializeUIAfterFrame()); } 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) { Debug.Log($"场景加载完成: {scene.name}"); StartCoroutine(ReinitializeUIAfterFrame()); } 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("添加输入模块到事件系统"); } } private void OnMainMenuClick() { Debug.Log("主菜单按钮点击"); SceneManager.LoadScene("MainMenu"); } private void OnStartClick() { Debug.Log("开始作战"); SceneManager.LoadScene("Fight"); } private void OnLoseClick() { Debug.Log("失败按钮点击"); SceneManager.LoadScene("Fight"); } private 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); } } } using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class NPC2 : MonoBehaviour { public GameObject image; public GameObject image1; public GameObject image2; public TextMeshProUGUI text; [Header("按钮设置")] public Button mainMenuButton; public Button startButton; public Button loseButton; public Button winButton; void Start() { // 初始化时隐藏所有按钮 if (mainMenuButton != null) mainMenuButton.gameObject.SetActive(false); if (startButton != null) startButton.gameObject.SetActive(false); if (loseButton != null) loseButton.gameObject.SetActive(false); if (winButton != null) winButton.gameObject.SetActive(false); // 确保UI元素正确隐藏 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); // 将按钮引用传递给DialogueManager if (DialogueManager.Instance != null) { DialogueManager.Instance.startButton = startButton; DialogueManager.Instance.loseButton = loseButton; DialogueManager.Instance.winButton = winButton; DialogueManager.Instance.image = image; DialogueManager.Instance.image1 = image1; DialogueManager.Instance.image2 = image2; DialogueManager.Instance.text = text; } else { Debug.LogError("DialogueManager实例未找到!"); } } void OnTriggerStay2D(Collider2D other) { if (other.CompareTag("Player") && Input.GetKeyDown(KeyCode.F)) { Debug.Log("玩家触发NPC对话"); // 激活UI元素 if (image != null) image.SetActive(true); if (image1 != null) image1.SetActive(true); if (image2 != null) image2.SetActive(true); if (text != null) text.gameObject.SetActive(true); // 启动对话 if (DialogueManager.Instance != null) { DialogueManager.Instance.StartStateDialogue(); // 根据状态显示对应按钮 switch (DialogueManager.Instance.currentState) { case DialogueManager.DialogueState.Before: if (startButton != null) { startButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(startButton.gameObject); } break; case DialogueManager.DialogueState.Win: if (winButton != null) { winButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(winButton.gameObject); } break; case DialogueManager.DialogueState.Lost: if (loseButton != null) { loseButton.gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(loseButton.gameObject); } break; } } } } } 我希望一开始就说话,而是通过npc2中的on triggerstay来进行调用
08-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值