0

I'm creating an array with a list of descriptions (strings) that I need to choose randomly and then assign to a text component in a gamobject. How do I do that? I've created the array but I don't know where to go from there. Can anyone help me with this?

public string[] animalDescriptions = 
{
    "Description 1",
    "Description 2",
    "Description 3",
    "Description 4",
    "Description 5",
};


void Start () 
{

    string myString = animalDescriptions[0];
    Debug.Log ("You just accessed the array and retrieved " + myString);

    foreach(string animalDescription in animalDescriptions)
    {
        Debug.Log(animalDescription);
    }
}

2 Answers 2

2
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Test : MonoBehaviour 
{
public Text myText;

public string[] animalDescriptions = 
{
    "Description 1",
    "Description 2",
    "Description 3",
    "Description 4",
    "Description 5",
};

void Start()
{
    string myString = animalDescriptions [Random.Range (0, animalDescriptions.Length)];
    myText.text = myString;
}
}
Sign up to request clarification or add additional context in comments.

Comments

1
string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];

You might want to store that new Random() somewhere else so that you don't seed a new one every time you want a new random description, but that's about it. You can do that by initializing your Random elsewhere, and simply using your instance of it in Start:

Random rand = new Random();
// ... other code in your class
void Start()
{
    string myString = animalDescriptions[rand.Next(animalDescriptions.Length)];
    // ... the rest of Start()
}

1 Comment

I popped that in but I'm getting an error on 'Next' : Assets/_Scripts/GameSetup.cs(23,67): error CS1061: Type UnityEngine.Random' does not contain a definition for Next' and no extension method Next' of type UnityEngine.Random' could be found (are you missing a using directive or an assembly reference?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.