我正在尝试销毁预制件,同时它仍然更改其比例,但它给了我错误"boxcolider2d 类型的对象已被销毁,但您仍在尝试访问它"。下面是我的代码
private void OnTriggerEnter2D(Collider2D collision)
{
StartCoroutine(ReScale(new Vector3(.5f, .5f), new Vector3(0.1f, 0.1f), collision));
Destroy(collision.gameObject,.5f);
}
private IEnumerator ReScale(Vector3 from, Vector3 to, Collider2D gameObjectCollided)
{
float progress = 0;
while (progress <= 1 && gameObjectCollided.gameObject != null)
{
gameObjectCollided.transform.localScale = Vector3.Lerp(from, to, progress);
progress += Time.deltaTime;
yield return null;
}
gameObjectCollided.transform.localScale = to;
}
我应该向代码中添加什么?
销毁后,您仍在尝试访问 IEnumerator 中的游戏对象:
gameObjectCollided.transform.localScale = to;
在设置比例之前,您可以添加检查以查看对象是否仍然存在:
if(gameObjectCollided.gameObject != null)
{
gameObjectCollided.transform.localScale = to;
}
启动对对象进行操作的协程,并立即销毁它。这没什么意义。基本上,你要求你的游戏引擎是"开始改变比例,但等待下一帧,并在这个帧上销毁它"。我想这不是你真正想做的。 我最好的赌注是你想要的是"在碰撞时,开始缩小物体,当你完成缩小它时,摧毁它"。 在这种情况下,您需要在协程中移动Destroy(collision.gameObject,.5f);
,作为最后一条指令(我会删除延迟(:
private IEnumerator ReScale(Vector3 from, Vector3 to, Collider2D gameObjectCollided)
{
float progress = 0;
while (progress <= 1 && gameObjectCollided.gameObject != null)
{
gameObjectCollided.transform.localScale = Vector3.Lerp(from, to, progress);
progress += Time.deltaTime;
yield return null;
}
gameObjectCollided.transform.localScale = to;
Destroy(collision.gameObject);
}
如果需要在销毁对象之前停止协程:
private Coroutine reScaleCoroutine;
private void OnTriggerEnter2D(Collider2D collision)
{
reScaleCoroutine = StartCoroutine(ReScale(new Vector3(.5f, .5f), new Vector3(0.1f, 0.1f), collision));
}
private void StopCoroutineMethod()
{
StopCoroutine(reScaleCoroutine);
}