C# 在游戏对象运行时销毁它';它仍在改变规模

C# 在游戏对象运行时销毁它';它仍在改变规模,c#,unity3d,game-development,C#,Unity3d,Game Development,我试图破坏一个预置,但它仍然改变它的规模,但它给我的错误是“类型为boxcolider2d的对象已被破坏,但你仍然试图访问它”。下面是我的代码 private void OnTriggerEnter2D(Collider2D collision) { StartCoroutine(ReScale(new Vector3(.5f, .5f), new Vector3(0.1f, 0.1f), collision)); Destroy(collision.gameObject,.5f

我试图破坏一个预置,但它仍然改变它的规模,但它给我的错误是“类型为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;

}
private void OnTriggerEnter2D(已碰撞R2D碰撞)
{
开始例行程序(重新缩放(新矢量3(.5f、.5f)、新矢量3(0.1f、0.1f)、碰撞);
销毁(碰撞。游戏对象,.5f);
}
私有IEnumerator重新缩放(向量3从、向量3到、碰撞的R2D GameObjectCollized)
{
浮动进度=0;

当(progress游戏对象被销毁后,您仍在尝试访问IEnumerator中的游戏对象:

gameObjectCollided.transform.localScale = to;
在设置比例之前,可以添加检查以查看对象是否仍然存在:

if(gameObjectCollided.gameObject != null) 
{
    gameObjectCollided.transform.localScale = to;
}

你启动一个对对象进行操作的协同程序,并立即销毁它。这没有什么意义。基本上,你要求游戏引擎“开始改变比例,但等待下一帧,并在这个帧上销毁它”。我想这不是你真正想要做的。 我的最佳选择是,你想要的是“在碰撞时,开始收缩对象,当你完成收缩时,销毁它”。 在这种情况下,您需要在协同程序中移动
Destroy(collision.gameObject.5f);
,作为最后一条指令(我会删除延迟):


为什么不在协同程序结束时销毁collision.gameobject呢?
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);
    }