Danro/Assets/Scripts/Behaviour/MessageController.cs

68 lines
2.8 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;
namespace RR.Common.Behaviour
{
public class MessageController : Sequencer
{
[Header("Настройки взаимодействия")]
[SerializeField] private bool isOneTime;
[Header("Префабы для сообщений")]
[SerializeField] private GameObject messagePlaceholderPrefab;
[SerializeField] private GameObject messageBubblePrefab;
private bool _isTriggered;
private Transform _placeholder;
private void OnTriggerEnter2D(Collider2D other)
{
if (IsExecuting || _isTriggered || !other.CompareTag("Player")) return;
InitializeSequence(other.gameObject);
if (isOneTime) _isTriggered = true;
}
/// <summary>
/// Получает или создает единственный Message Placeholder на сцене.
/// Placeholder становится дочерним объектом родителя MessageController.
/// </summary>
private Transform GetOrCreatePlaceholder()
{
if (_placeholder != null) return _placeholder;
// Ищем существующий placeholder среди дочерних объектов родителя
Transform parentTransform = transform.parent ? transform.parent : transform;
_placeholder = parentTransform.Find("Message Placeholder");
if (_placeholder == null)
{
// Создаем новый placeholder как дочерний объект родителя MessageController
GameObject placeholderInstance = Instantiate(messagePlaceholderPrefab, parentTransform);
placeholderInstance.name = "Message Placeholder";
_placeholder = placeholderInstance.transform;
}
return _placeholder;
}
/// <summary>
/// Добавляет сообщение с иконкой говорящего.
/// </summary>
/// <param name="speakerIcon">Иконка (спрайт) говорящего персонажа</param>
/// <param name="text">Текст сообщения</param>
public void Add(Sprite speakerIcon, string text)
{
Transform placeholder = GetOrCreatePlaceholder();
// Создаем Message и добавляем его в placeholder
GameObject messageInstance = Instantiate(messageBubblePrefab, placeholder);
Message message = messageInstance.GetComponent<Message>();
if (message)
{
message.Initialize(text, speakerIcon);
}
}
}
}