我有两个类:ItemAmmunition 和 ItemConsumables。它们的工作方式相同,但主要区别在于 ItemAmmunition 可以放置在 MainCell 和 AmmunitionCell 中,而 ItemConsumables 只能放置在 MainCell 中。这就是所有问题的开始!
MainCell 中的非工作代码。
public void OnDrop(PointerEventData eventData)
{
var a = eventData.pointerDrag.GetComponent<ItemConsumables>();
if (eventData.pointerDrag.GetComponent<ItemConsumables>() != null)
a = eventData.pointerDrag.GetComponent<ItemConsumables>();
else
a = eventData.pointerDrag.GetComponent<ItemAmmunition>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, dragItem.size);
}
else
{
dragItem.SetPosition(dragItem.gameObject, dragItem.prevMainCell, null);
CellOccupation(dragItem.prevMainCell, false, dragItem.size);
}
}
我什至无法正常找出其中包含的内容并写下来!如果我像这样执行此代码(第一个代码,但已被我更正。):
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag.GetComponent<ItemConsumables>() != null)
{
var a = eventData.pointerDrag.GetComponent<ItemConsumables>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, a.size);
}
else
{
dragItem.SetPosition(a.gameObject, a.prevMainCell, null);
CellOccupation(a.prevMainCell, false, a.size);
}
}
else
{
var a = eventData.pointerDrag.GetComponent<ItemAmmunition>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, a.size);
}
else
{
dragItem.SetPosition(a.gameObject, a.prevMainCell, null);
CellOccupation(a.prevMainCell, false, a.size);
}
}
}
事实证明这很长!我已经为此苦苦挣扎了很长时间。如何缩短这些 if-else 语句,以及一般如何分配这些变量?我不想发明自行车。