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

How do i pick randomly int,float,gameobject,string and transform from array in C#?

Discussion in 'Scripting' started by owlthesheep3, Oct 30, 2019.

  1. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    So i need help with randomly picking string,int,float,gameobject and transform from array.. so now i need to pick random fish module from the array, and the same for the other variables. Can anyone help me? i tried so many tutorials but they dont seem to work with me...
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    A typical way to choose a random thing out of an array is
    Code (CSharp):
    1. int randomIndex = UnityEngine.Random.Range(0, myArray.Length);
    2. var randomItem = myArray[randomIndex];
     
  3. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    but it doesnt work with gameobjects
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594
    It works. You just need array of GameObjects.
     
  5. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    It works exactly the same no matter what type of things are in your array. You have probably misunderstood the source of some error you are getting.
     
  6. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    Why don't you try posting some code that you've tried but doesn't work, and we can advise you on what's wrong with it?
     
    Joe-Censored likes this.
  7. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    Error CS0029 Cannot implicitly convert type 'int' to 'UnityEngine.GameObject'

    Code :
    Code (CSharp):
    1. public GameObject[] fishModels;
    2.  
    3. void Start(){
    4. GameObject randomIndex = UnityEngine.Random.Range(0, fishModel.Length);
    5. }
     
  8. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594
    You missed one step.
    Index is an int.
    You pass index int to get element of an array.
     
    Joe-Censored likes this.
  9. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    Code (csharp):
    1. int randomIndex = UnityEngine.Random.Range(0, fishModels.Length);
    2. GameObject randomObject = fishModels[randomIndex];
     
    Joe-Censored likes this.