我正在尝试销毁预制件,但它仍会更改其比例,但是它给我一个错误:“ 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;
}
我应该在代码中添加什么?
答案 0 :(得分:1)
在销毁IEnumerator之后,您仍在尝试访问GameObject:
gameObjectCollided.transform.localScale = to;
您可以在设置比例之前添加检查以查看对象是否仍然存在:
if(gameObjectCollided.gameObject != null)
{
gameObjectCollided.transform.localScale = to;
}
答案 1 :(得分:0)
您启动对对象进行操作的协程,并立即销毁它。这没有什么意义。基本上,您要问您的游戏引擎是“开始更改比例,然后等待下一帧,并在此帧上销毁它”。我想这不是您真正想要做的。
我最好的选择是,您想要的是“在碰撞时,开始缩小对象,完成缩小后,销毁它”。
在这种情况下,您需要将<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="row p-3">
<div class="col-12">
<h5 class="text-center">Color Legend</h5>
</div>
<div class="col-12">
<div class="row">
<div class="col-3">
<i class="far fa-circle circle px-2">I</i>
</div>
<div class="col-9">
<p>Not visited topic</p>
</div>
</div>
</div>
<div class="col-12">
<div class="row">
<div class="col-3">
<i class="far fa-circle circle px-2" style="color:#016fc9;">I</i>
</div>
<div class="col-9">
<p>Visted topic</p>
</div>
</div>
</div>
<div class="col-12">
<div class="row">
<div class="col-3">
<i class="far fa-circle circle px-2" style="color:#00bfa5">I</i>
</div>
<div class="col-9">
<p>Visted topic, pop-up question <strong>successfully</strong> answered.</p>
</div>
</div>
</div>
<div class="col-12">
<div class="row">
<div class="col-3">
<i class="far fa-circle circle px-2" style="color:#f44336">I</i>
</div>
<div class="col-9">
<p>Visted topic, pop-up question <strong>failed</strong> after visting.</p>
</div>
</div>
</div>
</div>
移至协程中,这是最后一条指示(我将删除延迟):
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);
}