Files
aibis-dream/Assets/Scripts/FixSystemNew/CoolingMachine/BottleSlot.cs
T
2024-12-27 04:45:38 +08:00

120 lines
3.3 KiB
C#

using System;
using UnityEngine;
namespace AibisDream.FixSystem
{
[RequireComponent(typeof(Collider2D))]
public class BottleSlot : MonoBehaviour
{
public event Action<CoolingBottle> InsertSlotEvent;
public event Action RemoveSlotEvent;
public CoolingBottleData initBottleData;
private CoolingBottle _curBottle;
private GameObject _bottlePrefab;
private bool _inShelf;
private void Start()
{
InitRefs();
InitBottle();
}
private void InitRefs()
{
var shelf = GetComponentInParent<BottleShelf>();
// 根据在瓶架上还是机器中确定操作
_inShelf = shelf != null;
_bottlePrefab = Resources.Load<GameObject>("Prefabs/Fix/Bottle");
}
private void InitBottle()
{
if (string.IsNullOrEmpty(initBottleData.name)) return;
var newBottle = Instantiate(_bottlePrefab, transform).GetComponent<CoolingBottle>();
_curBottle = newBottle;
// 加载瓶子数据
newBottle.Load(initBottleData);
newBottle.curSnapSlot = this;
}
/// <summary>
/// 与瓶子发生碰撞时
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter2D(Collider2D other)
{
// 如果当前Slot里已经有瓶子了,就返回
if (_curBottle != null) return;
// 尝试获取瓶子
if (other.gameObject.TryGetComponent<CoolingBottle>(out var bottle))
{
bottle.targetSnapSlotSet.Add(this);
}
}
/// <summary>
/// 瓶子离开时
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit2D(Collider2D other)
{
// 尝试获取瓶子
if (other.gameObject.TryGetComponent<CoolingBottle>(out var bottle))
{
bottle.targetSnapSlotSet.Remove(this);
}
}
/// <summary>
/// 移除当前瓶子
/// </summary>
public void RemoveBottle()
{
_curBottle = null;
RemoveSlotEvent?.Invoke();
}
/// <summary>
/// 插入时触发
/// </summary>
/// <param name="coolingBottle"></param>
public void InsertSlot(CoolingBottle coolingBottle)
{
_curBottle = coolingBottle;
_curBottle.transform.parent = transform;
// 在架子上才正过来
if (_inShelf)
{
coolingBottle.Rotate(true);
}
}
public void ChangeSlot(CoolingBottle coolingBottle)
{
InsertSlotEvent?.Invoke(coolingBottle);
}
/// <summary>
/// 是否有冷却液
/// </summary>
/// <returns>瓶子</returns>
public CoolingBottle GetCurBottle()
{
return _curBottle;
}
public void DestroyBottle()
{
if (_curBottle)
{
_curBottle.transform.parent = null;
Destroy(_curBottle.gameObject);
_curBottle = null;
}
}
}
}