Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to check last activated object to avoid randomly activaing it again?

Discussion in 'Scripting' started by frozendog_bren, Aug 4, 2015.

  1. frozendog_bren

    frozendog_bren

    Joined:
    Nov 29, 2014
    Posts:
    19
    What i'm trying to do seems simple, but my programing skills are S***.

    For example:

    Whenever i press a button (i get this part), the scripts calls a method that will randomly set a game object, in my array, active, but when i press the button again, it can try to activate the recently activated object again. So it must check if the next number generated is already active. If yes, it generates once more. I've tried several things, but failed.

    here's a piece of the script:

    Code (CSharp):
    1. GameObject[] areas;
    2. int randomAreaNum;
    3.      
    4. public void OpenArea()
    5. {
    6.          randomAreaNum = Random.Range (0, areas.Length);
    7.          areas[randomAreaNum].SetActive(true);
    8.      
    9. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you could try a do...while loop

    Code (csharp):
    1.  
    2. do
    3. {
    4. randomAreaNum = Random.Range (0, areas.Length);
    5. }
    6. while(areas[randomAreaNum].activeSelf = true);
    7.  
    8. areas[randomAreaNum].SetActive(true);
    9.  
    this will infinite loop if all the items are active, you'll need to account for that and either add it to the while(...) clause or just encompass the whole thing in an if.

    do...while c# msdn
    https://msdn.microsoft.com/en-us/library/370s1zax.aspx
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    alternatively you can have two lists "open" and "closed" and move the area from one list to another (don't use arrays for this they don't shrink and you'll have null gaps)
     
  4. frozendog_bren

    frozendog_bren

    Joined:
    Nov 29, 2014
    Posts:
    19
    Thanks, dude! I'll try it.