Hey guys so basically I am prorgramming a top down 3D cubed civilization game and I am having an issue. I have it so that when you click on the signs, a screen opens up with the shop… the way I have it set up is when the sign is clicked, the GameObject that holds the UI for the shop is set to active as it is originally not active. Now I want it so that whenever this gameobject becomes active, a new value from the variable minCustomers is generated in a text field.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ShopManager : MonoBehaviour {
public int minWorkers;
public int maxWorkers;
public int minCustomers;
public int maxCustomers;
public Text workers;
public Text customers;
public bool isOpenSign;
public GameObject sign;
void Start() {
maxWorkers = 5;
maxCustomers = 10;
isOpenSign = false;
}
void AddCustomer() {
if (!isOpenSign && sign.activeSelf) {
isOpenSign = true;
minCustomers = Random.Range (0, 19);
} else {
isOpenSign = false;
}
}
void Update() {
workers.text = "Workers: " + minWorkers;
customers.text = "Customers: " + minCustomers;
AddCustomer ();
}
}
For some reason, this just causes the bool to constantly go true and false as well as the Random.Range generates numbers per the second. I know it has to do with because I call the function within update but I have to because I need it to constantly be checking if the UI is active or not…
So I’m confused, if anyone could help that would be great
In that case, you should simply put the code for that in the OnEnable method. This fires when the object becomes activate.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ShopManager : MonoBehaviour {
public int minWorkers;
public int maxWorkers = 5;
public int minCustomers;
public int maxCustomers = 10;
public Text workers;
public Text customers;
public bool isOpenSign = false;
public GameObject sign;
void Awake() {
minCustomers = Random.Range (0, 19);
workers.text = "Workers: " + minWorkers;
customers.text = "Customers: " + minCustomers;
}
}
You’re checking if the sign is not open, which is great. But in the body of that if statement, you set isOpenSign to true. The problem with that is you have an else statement which sets the sign to false which, next frame, will cause your if statement is trigger because isOpenSign is set to false. Thus causing a really weird loop.
void AddCustomer() {
if (!isOpenSign && sign.activeSelf) {
isOpenSign = true; // You set this to true here, which next update will trigger the else case
minCustomers = Random.Range (0, 19);
} else {
isOpenSign = false; // You now set it to false, which will trigger the if(!isOpenSign && sign.activeSelf) statement.
}
}
A solution to your problem, why not you have a public function that is called when this sign becomes active?