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

Activate Random Objects

Discussion in '2D' started by Thril3r, Dec 20, 2014.

  1. Thril3r

    Thril3r

    Joined:
    Dec 6, 2013
    Posts:
    19
    Hi, I have 10 (Null) objects and I want to activate them as Score Object or Death Object, but I want to activate them randomly at random time between 5-15 seconds.

    I thought to make 2 scripts one for score and one for death and use something like this to enable one of the script. but how can I achieve it randomly?
    Code (CSharp):
    1. gameObject.GetComponent<Score> ().enabled = true;
    Help.jpg unity help.jpg

    LE: Or a better way should be to randomly generate a number from 1-10 and if the number = Object name randomly activate one of the scripts on that object?
     
    Last edited: Dec 21, 2014
  2. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    You could try this. Though it's in Unity's javascript.

    Code (JavaScript):
    1. var score : GameObject;
    2. var death : GameObject;
    3. var gamearray : GameObject[];
    4.  
    5. function Start()
    6. {
    7. gamearray = new GameObject[10];
    8. InvokeRepeating("ChangeArray", Random.Range(5, 15), Random.Range(5, 15));
    9.  
    10. for(var i : float = 0; i < 10; i++)
    11. {
    12.     var chooseRandomly : boolean = (Random.value < 0.5);
    13.     if(chooseRandomly == true)
    14.    {
    15.        gamearray[i] = score;
    16.    }
    17.    else
    18.    {
    19.        gamearray[i] = death;
    20.    }
    21. }
    22. }
    23.  
    24. function ChangeArray()
    25. {
    26. for(var i : float = 0; i < 10; i++)
    27. {
    28.     var chooseRandomly : boolean = (Random.value < 0.5);
    29.     if(chooseRandomly == true)
    30.    {
    31.        gamearray[i] = score;
    32.    }
    33.    else
    34.    {
    35.        gamearray[i] = death;
    36.    }
    37. }
    38. }
     
    Thril3r likes this.
  3. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    This way you will have an array of gameobjects that changes every 5-15 seconds with randomly changed score or death at positions 0-9. I'll gladly help you if there're other problems.
     
    Thril3r likes this.
  4. Thril3r

    Thril3r

    Joined:
    Dec 6, 2013
    Posts:
    19
    Thank you! I was in a little vacation, I will test this today or tomorrow. :D