- Home /
Too subjective and argumentative
Unity crashes after I destroy a gameobject
So I wrote what I thought would be a simple script for destroying an object after doing something specific, but it crashes my game?
public class DestroyThis : MonoBehaviour
{
public bool hasTalked;
void Start()
{
hasTalked = false;
}
private void OnTriggerEnter2D(Collider2D player)
{
while (hasTalked == true)
{
if (player.gameObject.tag == "Player")
{
DestroyGameObject();
}
}
}
void DestroyGameObject()
{
Destroy(gameObject);
}
}
hasTalked becomes true once you talk to an npc, but once it does and the player triggers the object, the game literally freezes and there's no way to escape other than ending unity through Task Manager. What is the problem??
Answer by Casiell · Feb 27, 2020 at 11:57 AM
while (hasTalked == true)
This line creates an infinite loop as hasTalked never changes inside of it, so the exit condition never happens.
You probably want:
if (hasTalked == true)
instead
While is the most dangerous loop for program$$anonymous$$g :D its really scares me
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Problem with timed code-execution (audioplay and object destruction) 1 Answer
How come when the player runs into the coin it won't destroy? 1 Answer
Is there anyway to make an object impenetrable? 1 Answer
Easy collision script not working, don't understand. 2 Answers