using UnityEngine; using System.Collections; using Hallucinate.Audio; public class TreasureItem : MonoBehaviour { [Header("Cài đặt UI thông báo")] public GameObject notificationText; // Kéo Text "Đã nhặt Cổ vật" vào đây [Header("Cài đặt Âm thanh")] public string pickupSound = "Item_Pickup"; [Header("Cấu hình Tag")] public string playerTag = "Player"; // Biến cờ để tránh việc va chạm 2 lần trong cùng 1 frame private bool isCollected = false; private void Start() { // Đảm bảo UI thông báo luôn tắt khi bắt đầu game if (notificationText != null) { notificationText.SetActive(false); } } private void OnTriggerEnter(Collider other) { // 1. Chỉ xử lý khi chạm đúng Player và rương chưa bị nhặt if (!isCollected && other.CompareTag(playerTag)) { PlayerInventory player = other.GetComponentInChildren(); if (player == null) player = other.GetComponentInParent(); if (player != null) { // Khóa lại để không bị kích hoạt nhiều lần isCollected = true; // 2. Tăng số lượng rương đang giữ player.treasuresCollected++; Debug.Log($"[Chest] NHẶT THÀNH CÔNG! Số rương hiện tại: {player.treasuresCollected}"); // 3. Cập nhật sao trên HUD (Sử dụng hàm Unity 6: FindAnyObjectByType) FinishGate gate = Object.FindAnyObjectByType(); if (gate != null) { gate.UpdateStarsUI(player.treasuresCollected); } // 4. Kích hoạt trạng thái truy đuổi cho toàn bộ Enemy AI SetEnemiesAlertState(true); // 5. Chạy âm thanh nhặt đồ if (AudioManager.Instance != null) { AudioManager.Instance.Play(pickupSound, position: transform.position); } // 6. Xử lý hiện UI và làm biến mất rương an toàn StartCoroutine(HandlePickupRoutine()); } } } private void SetEnemiesAlertState(bool state) { // Sử dụng hàm chuẩn Unity 6+ EnemyAI[] allEnemies = Object.FindObjectsByType(FindObjectsSortMode.None); foreach (EnemyAI enemy in allEnemies) { if (enemy != null) { enemy.playerHasArtifact = state; } } } private IEnumerator HandlePickupRoutine() { // Ẩn rương đi trước (tắt hiển thị và va chạm) HideTreasureModel(); // Bật UI thông báo "Đã nhặt Cổ vật" if (notificationText != null) { notificationText.SetActive(true); } // Chờ 2 giây yield return new WaitForSeconds(2f); // Tắt UI thông báo if (notificationText != null) { notificationText.SetActive(false); } // Khi UI đã xử lý xong, mới chính thức tắt hoàn toàn GameObject rương gameObject.SetActive(false); } private void HideTreasureModel() { // Tắt va chạm chính của rương Collider col = GetComponent(); if (col != null) col.enabled = false; // Tắt model hiển thị 3D của rương (bao gồm cả object cha và con) MeshRenderer[] renderers = GetComponentsInChildren(); foreach (MeshRenderer r in renderers) { r.enabled = false; } } }