86 lines
3.5 KiB
C#
86 lines
3.5 KiB
C#
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;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|