Hello, I’m trying to print a random text string to a text object located into my project so that every time the level loads a random piece of the string will appear. I have managed to make it so that the code selects a piece from the string but I’m unable to make it display instead of the text piece on my level. What am I missing from the code below that would allow this to happen? The script is attached to a game object and seems to work apart from displaying it onto a chosen text object.
Thank you for your help! I’m new to this so anything would be helpful.
public class RandomLearningText : MonoBehaviour
{
public Text randomText;
public string[] TestArray = new string[3];
void Start ()
{
TestArray [0] = ("test 1");
TestArray [1] = ("test 2");
TestArray [2] = ("test 3");
string randomText = TestArray[Random.Range(0, TestArray.Length)];
}
}
I can see what you mean from that tutorial but it won’t work with the string I have due to me wanting to randomly select a part of the string and to then display that rather than a single piece of text so I’m still currently stuck with it.
I think you misunderstand
string randomText = TestArray[Random.Range(0, TestArray.Length)];
should be
randomText.text = TestArray[Random.Range(0, TestArray.Length)];
You already declare randomText as a text object. So you need to assign a string to it’s text. This picks a random value from your array and assigns it to your text object. Now, if you are trying to do a substring from a string, that’s a different story, but that’s just not what you are showing. Here you are picking a random string from an array.
If you want part of a string, you’ll need to use subString, pass it a random start number, and a random length and then assign that to your randomText.text.
Like Pavlon said, the way it is now, you’re creating a NEW string variable named “randomText” that is overwriting the one you have declared at the top.