Unity实现物件挂载到不同父节点
首先需要一个物件对象
public class KitchenObject : MonoBehaviour
{
public KitchenObjectHolder Holder { get; set; }
public void ResetHolder()
{
if (Holder == null)
return;
Holder.KitchenObject = null;
Holder= null;
}
}
然后是物件持有者对象
public class KitchenObjectHolder :MonoBehaviour
{
[SerializeField]
private Transform kitchenObjectParent;
public KitchenObject KitchenObject { get; set; }
public Transform GetKitchenObjectParentTransform()
{
return kitchenObjectParent;
}
public void TrySwapKitchenObject(KitchenObjectHolder another)
{
MoveKitchenObject(this, another);
}
private static void MoveKitchenObject(KitchenObjectHolder holder1, KitchenObjectHolder holder2)
{
if ((holder1.KitchenObject!=null) && (holder2.KitchenObject!=null))
return;
if ((holder1.KitchenObject==null ) && (holder2.KitchenObject==null))
return;
if(holder1.KitchenObject != null)
{
holder2.HoldKitchenObject(holder1.KitchenObject);
}
else if(holder2.KitchenObject != null)
{
holder1.HoldKitchenObject(holder2.KitchenObject);
}
}
public bool HoldKitchenObject(KitchenObject kitchenObject)
{
if (this.KitchenObject != null)
return false;
kitchenObject.ResetHolder();
kitchenObject.Holder = this;
this.KitchenObject = kitchenObject;
kitchenObject.transform.parent = GetKitchenObjectParentTransform();
kitchenObject.transform.localPosition = Vector3.zero;
return true;
}
}
代码的核心逻辑就是将物件的transform的parent设置为持有者对象上的一个transform。
然后制作prefab。