由于不能直接删除子物体,所以需要先将子物体的父级置空,然后才可以销毁
void showBulletsCount()
{
const int spacing = 50;
int childCount = BulletsCountMount.transform.childCount;
int differ = childCount - _bulletClipRemain;
if (differ != 0)
{
if (differ < 0)
{//少了补
UISprite showBullet = Instantiate(Resources.Load<UISprite>("Prefabs/bullets/showBullet"), Vector3.zero, Quaternion.identity, BulletsCountMount.transform);
showBullet.name = "Bullet" + childCount;
showBullet.transform.localPosition = new Vector3(childCount * showBullet.width + spacing, 0);
}
else
{//多了减
GameObject go = BulletsCountMount.transform.GetChild(childCount - 1).gameObject;
go.transform.SetParent(null);//删除子物体先要取消父级挂载
DestroyObject(go);
}
}
}
这是我做的显示当前剩余子弹的UI,可以根据需要自行调整