Files
aibis-dream/Assets/Scripts/FixSystemNew/CoolingMachine/BottleSlot.cs
T
2024-12-24 13:52:41 +08:00

79 lines
2.3 KiB
C#

using System;
using UnityEngine;
namespace AibisDream.FixSystem
{
[RequireComponent(typeof(Collider2D))]
public class BottleSlot : MonoBehaviour
{
public event Action<CoolingBottle> InsertSlotEvent;
public CoolingBottleData initBottleData;
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>();
// 加载瓶子数据
newBottle.Load(initBottleData);
newBottle.curSnapSlot = this;
}
/// <summary>
/// 与瓶子发生碰撞时
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Enter: " + other.gameObject.name);
// 尝试获取瓶子
if (other.gameObject.TryGetComponent<CoolingBottle>(out var bottle))
{
bottle.targetSnapSlot = this;
}
}
/// <summary>
/// 瓶子离开时
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit2D(Collider2D other)
{
Debug.Log("Exit: " + other.gameObject.name);
// 尝试获取瓶子
if (other.gameObject.TryGetComponent<CoolingBottle>(out var bottle))
{
bottle.targetSnapSlot = null;
}
}
/// <summary>
/// 插入时触发
/// </summary>
/// <param name="coolingBottle"></param>
public void InsertSlot(CoolingBottle coolingBottle)
{
coolingBottle.transform.parent = transform;
coolingBottle.SwitchColliderSize(_inShelf);
InsertSlotEvent?.Invoke(coolingBottle);
}
}
}