- Home /
How can I set active a random Ui object from a list on a button press then reset it after the button pressed?
How can I set a random ui object active from a list of ui objects on button click then reset the list so that if i click again it will activate another random ui object? So basically im making a chest reward on the ui and the player can click on the chest image to open it then I set active a random ui object from a list and that rewards them. But after that if the player clicks the chest button again the same ui object pops back up because its already set active. I want it to where if the player clicks the chest button again i need another random ui object from the list to activate. Thanks for the help
Answer by xxmariofer · Jul 11, 2019 at 06:27 AM
private List<GameObject> activeUIobjects = new List<GameObject>();//this is just in case you want to desactivate it
private List<GameObject> inactiveUIobjects = new List<GameObject>();//fill your list
public void ActivateRandom()
{
int random = Random.Range(0, inactiveUIobjects.Count);
inactiveUIobjects[random].SetActive(true);
activeUIobjects.add(inactiveUIobjects[random]);
inactiveUIobjects.RemoveAt(random);
}
Not tested but should work
Hmm I'm getting red squiggles in the
int random = Random.Range(0, inactiveUIobjects); (the inactiveUiobjects part)
and then on the add part of the activeUiobjects.add
also would i attach this to a ui elememt for the list then just add this to a button click event?
Ok the first part is fixed with the ".Count" added
but the .add part still gets the error nope fixed it sorry just capitalize the Add totally forgot facepalm
Hmm thanks a ton for the answer. It seems to be working but not quite here is how it goes I attached the script to game object changed the private list on inactiveuiobjects to public so i could add the ui objects to list from the editor. then I take the chest Button and drag to gameobject with the script attached to it to the on click button event and set it to "ActivateRandom()"
then when I click the button it works it set actives one ui object from the list, But when I close the ui object as in press its button attached to it to set active to false. The Chest button cant activate it again. So basically if its been chosen from the list already It cant be activated again after ive already deactivated it witht the other button
Alrighty Final Comment haha, I figured it out exactly what I wanted it to do. If you don't want it removed at all and would like it to keep activating random form the list then just remove the line "inactiveUIobjects.RemoveAt(random);
Awesome. Thanks a ton man
i thought you wanted to only desactivate it once my fault, and sorry for the mistakes i code it in the answer without the inteligence
No no it's perfect! Thanks so much for taking time to answer. It works just fine and taught me alot!
Cheers :)