Why doesn't this if-statement work?
I'm creating a game where you click boxes and gain points by doing so. I want to create new boxes when the game starts and when the box gets destroyed. Instead, this script just creates new boxes every frame. I don't know why this doesn't work, maybe I'm doing it all wrong, I'm pretty new to Unity and c#.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxScript : MonoBehaviour {
private bool boxExists = false;
private Vector3 startPos = new Vector3(-10, 0, 0);
public GameObject box;
private void Update() {
if (!boxExists) {
Instantiate(box, startPos, Quaternion.identity);
Destroy(box);
boxExists = true; }
}
}
What gameObject is box
? Is a gameObject holding the BoxScript
? If so, it's probably because the newly instantiated box run once the Update
function, and thus, creates a new box before it's itself destroyed.
Answer by Sgt_Spike · Jul 18, 2018 at 12:59 PM
Hi there. Don't quote me on this but I'm pretty sure it's not working because you are using Update(). Update executes so quickly that your code won't even get to 'boxExists = true', so basically it always equals false and creates a new box using 'Instantiate'. Try changing your code to this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxScript : MonoBehaviour {
private bool boxExists = false;
private Vector3 startPos = new Vector3(-10, 0, 0);
public GameObject box;
private void Start()
{
InvokeRepeating("YourMethod", 0f, 0.05f);
}
private void YourMethod() {
if (!boxExists) {
Instantiate(box, startPos, Quaternion.identity);
Destroy(box);
boxExists = true; }
}
}
'YourMethod' you can change to what you want, and '0.05f' is how long until 'YourMethod' will be executed again. Try that and let me know if it works. :D
Thanks for replying @HyperGamer87 ! I will try the code and let you know if it worked.
@HyperGamer87 I have implemented your code to my game and now it works perfectly, thanks a lot!