Hệ thống tương tác đa dụng (Nhấn E)
C# Code
using UnityEngine;
using TMPro;
// 1. Interface cho tất cả các đối tượng có thể tương tác
public interface IInteractable
{
// Hành động sẽ xảy ra khi người chơi tương tác
void Interact();
// Văn bản sẽ hiển thị khi người chơi nhìn vào đối tượng
string GetInteractionPrompt();
}
// 2. Script chính gắn vào người chơi
public class InteractionSystem : MonoBehaviour
{
public Camera playerCamera;
public float interactionDistance = 3f;
public TextMeshProUGUI interactionPromptUI;
void Update()
{
// Tạo một ray từ camera hướng về phía trước
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
RaycastHit hit;
// Kiểm tra xem ray có chạm vào vật thể nào trong tầm tương tác không
if (Physics.Raycast(ray, out hit, interactionDistance))
{
// Lấy component IInteractable từ vật thể chạm phải
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
// Nếu có, hiển thị prompt và lắng nghe input
if (interactable != null)
{
interactionPromptUI.text = interactable.GetInteractionPrompt();
interactionPromptUI.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
interactable.Interact();
}
return;
}
}
// Nếu không có vật thể nào trong tầm, ẩn prompt
interactionPromptUI.gameObject.SetActive(false);
}
}
// 3. Ví dụ: một công tắc có thể tương tác
public class SwitchInteract : MonoBehaviour, IInteractable
{
private bool isOn = false;
public Light connectedLight; // Kéo một đối tượng Light vào đây
public string GetInteractionPrompt()
{
return isOn ? "Press E to Turn Off" : "Press E to Turn On";
}
public void Interact()
{
isOn = !isOn;
if (connectedLight != null) {
connectedLight.enabled = isOn;
}
Debug.Log(isOn ? "Switch turned ON" : "Switch turned OFF");
}
}Một hệ thống linh hoạt cho phép người chơi tương tác với nhiều loại đối tượng (cửa, vật phẩm, NPC, công tắc) chỉ bằng một nút bấm (E) khi ở trong tầm, kèm hiển thị gợi ý trên màn hình.