Afterparty/Assets/Scripts/Player/PlayerInteraction.cs
2026-01-11 17:04:23 +03:00

87 lines
3.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
public float interactionDistance = 3f;
public LayerMask interactionLayer;
private Outline previousOutline = null;
private GameObject currentInteractableObject = null;
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
// Сбрасываем текущие найденные объекты в начале каждого кадра
IInteractable interactable = null;
currentInteractableObject = null;
Outline currentOutline = null;
if (Physics.Raycast(ray, out hit, interactionDistance, interactionLayer))
{
Transform currentTransform = hit.collider.transform;
// Ищем IInteractable, поднимаясь по иерархии
while (currentTransform != null)
{
IInteractable potentialInteractable = currentTransform.GetComponent<IInteractable>();
if (potentialInteractable != null)
{
// *** ГЛАВНОЕ ИЗМЕНЕНИЕ ***
// Проверяем, есть ли у объекта описание в данный момент.
// Если описание пустое, значит, объект неактивен.
if (!string.IsNullOrEmpty(potentialInteractable.GetDescription()))
{
interactable = potentialInteractable;
currentInteractableObject = currentTransform.gameObject;
currentOutline = currentTransform.GetComponent<Outline>();
break; // Нашли валидный интерактивный объект, выходим из цикла
}
}
currentTransform = currentTransform.parent;
}
}
// Логика выключения подсветки для предыдущего объекта
if (previousOutline != null && previousOutline != currentOutline)
{
previousOutline.enabled = false;
}
// Если мы нашли валидный интерактивный объект (с описанием)
if (interactable != null)
{
// Включаем подсветку
if (currentOutline != null)
{
currentOutline.enabled = true;
previousOutline = currentOutline;
}
// Обрабатываем нажатие клавиши
if (Input.GetKeyDown(KeyCode.F))
{
interactable.Interact();
// После взаимодействия подсветка должна сразу пропасть,
// поэтому сбрасываем ее здесь, не дожидаясь следующего кадра.
if (currentOutline != null)
{
currentOutline.enabled = false;
}
previousOutline = null;
}
}
else // Если не нашли ничего интерактивного
{
// Убеждаемся, что старая подсветка выключена
if (previousOutline != null)
{
previousOutline.enabled = false;
previousOutline = null;
}
}
}
}