Search Unity

Beginner: How to Randomly Select Some Objects

Discussion in '2D' started by kalliste, May 12, 2015.

  1. kalliste

    kalliste

    Joined:
    Apr 3, 2015
    Posts:
    3
    I am very new to all of this, and apologize if these are very basic questions - but this seems like an incredibly helpful community from what I've read, and I'm hoping someone can steer me in the right direction.

    I am trying to make a simple 2D hidden object game - a scene with some findable objects on it, which disappear when found.

    I have the basic scenes created, and the objects destroy when clicked. What I'm trying to figure out is how to have a smaller set of objects be findable, text objects update to show their names, and cross off when found. I thought switching a tag would be a way to do that, but I don't know how to actually pick them.

    So I have 32 items total, and when the scene loads I want 12 of them to be randomly selected, and those 12 are tagged as clickable and the names are listed below, and the other 20 are still in the scene, but aren't clickable.

    I feel like it should be fairly simple, but I can't come up with the best way to do it. I am new to all this, but I would love if someone could give me some pointers and steer me in the right direction.

    Thank you so much in advance!
     
  2. Aaron_T

    Aaron_T

    Joined:
    Sep 30, 2014
    Posts:
    123
    If all 32 items have the same tag (set in the inspector in the editor), you can use GameObject.FindGameObjectsWithTag to get an array of every object in the scene with that tag. From there, you can select 12 of those items in the array at random (there a various ways to do this, I'll let you come up with something). And then, with those 12 which were selected, you can edit them so that they're "clickable" (this sounds like something that you will program manually).

    Some pseudocode, for example:
    Code (csharp):
    1.  
    2. GameObject[] allObjects = GameObject.FindGameObjectsWithTag("SomeSpecificTag");
    3. GameObject[] chosenObjects = new GameObject[12];
    4.  
    5. //Some code here to select 12 objects from allObjects however you choose and add them to chosenObjects from slots 0 to 11.
    6.  
    7. foreach (GameObject go in chosenObjects)
    8. go.GetComponent<YourScriptNameHere>().SetIsClickable(true);
    9.  
    Where "YourScriptNameHere" is the name of whatever script controls the behavior of clickable items, and "SetIsClickable" is a public function within that script.