[英]How I can fix the “The object of type 'GameObject' has been destroyed but you are still trying to access it.” Unity
I have 2 monsters and 1 player.我有 2 个怪物和 1 个玩家。 when players shoot, i get this mistake and they stop shooting.当球员投篮时,我犯了这个错误,他们停止投篮。 I have the same code for players, but players can keep shooting.我对玩家有相同的代码,但玩家可以继续射击。 I think the problem is with "destroy" but I can not find a solution enter image description here我认为问题在于“破坏”,但我找不到解决方案在此处输入图像描述
public class SpawnBulletController : MonoBehaviour
{
public GameObject bullet;
public float interval = 1F;
// Use this for initialization
void Start () {
InvokeRepeating("ShootBullet", interval, interval);
}
void ShootBullet()
{
GameObject g = Instantiate(bullet, transform.position, Quaternion.identity);
}
}
public class BorderCollision : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag != "Player")
Destroy(other.gameObject);
}
}
When your collider hits any GameObject that has no "Player" tag the GameObject will be destroyed this is wrong.当您的对撞机击中任何没有“玩家”标签的游戏对象时,游戏对象将被销毁,这是错误的。
you should try你应该试试
private void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.tag == "Monster")
Destroy(collider.gameObject);
}
And if you want to destroy more with the same code but not with the same tag you should try.如果您想使用相同的代码但不使用相同的标签销毁更多内容,您应该尝试。
private void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.tag == "Monster" || collider.gameObject.tag == "Monster2")
Destroy(collider.gameObject);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.