Search Unity

Randomly pick text from array

Discussion in 'Scripting' started by owlthesheep3, Sep 2, 2019.

  1. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    I want to make an splash text something like minecraft has, but i dont know how to randomly pick text for it. I've made string array variable (public string[] arrayText) and ive written all the text, im not that professional at unity and scripting so can somebody help me? Also do i need to have text written in code or in inspector? i use unity 3D and Visual Studio 2019 community. thanks:)
     
  2. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    BY THE WAY heres the code that i have if someone needs it
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SplashText : MonoBehaviour
    6. {
    7.     public string[] splashText;
    8.     void Start()
    9.     {
    10.        
    11.     }
    12. }
    13.  
     
  3. Neriad

    Neriad

    Joined:
    Feb 12, 2016
    Posts:
    125
    You would need to take a random index to look into the array.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class SplashText : MonoBehaviour
    7. {
    8.     public string[] splashText;
    9.  
    10.     void Start ()
    11.     {
    12.         Debug.Log(GetRandomSplashText());
    13.     }
    14.  
    15.     string GetRandomSplashText ()
    16.     {
    17.         // Gets a random number between 0 and the number of strings in the array
    18.         int random = Random.Range(0, splashText.Length);
    19.         // Returns the index random from the string array
    20.         return splashText[random];
    21.     }
    22. }
     
  4. owlthesheep3

    owlthesheep3

    Joined:
    May 13, 2019
    Posts:
    35
    Thank you so much! I'm sorry I posted this 2 times as I needed to make this quick!