- Home /
Question by
ebebil · Sep 12, 2021 at 03:29 AM ·
if-statements
how to destroy by the time
hello, i am trying to do timed destruction but i can't. can you show me where is my mistake and thank you and this is my code
void Update() { int counter = 0; if (counter <= 0) {
counter = counter++;
Debug.Log(counter);
}
if (counter == 200)
{
Destroy(gameObject);
}
}
Comment
Answer by ryanlin138 · Sep 12, 2021 at 06:23 AM
You are declaring the counter variable in the Update loop. Try moving the int counter = 0; out of the Update(). Also, counter = counter++ is unnecessary, just counter++ is enough.
public class ExampleClass : MonoBehaviour
{
int counter = 0;
void Update()
{
if (counter <= 0)
{
counter++;
//Debug.Log(counter);
}
if (counter == 200)
{
Destroy(gameObject);
}
}
}
Another way to do this is using an overload of the Destroy() method.
public class TimedDestroy : MonoBehaviour
{
public float timeBeforeDestroy = 10f; // 10 Seconds
public void Start()
{
Destroy(gameObject, timeBeforeDestroy);
}
}
Your answer
Follow this Question
Related Questions
Combining if Statements 1 Answer
Single line if statement with many conditions or several single-conditioned if statements 1 Answer
C# the position of the object 1 Answer
Creating a Loadout 1 Answer
If gameobject moves do this 1 Answer