What are the steps for the player to be able to create a list of items, then have the computer select and show a single item from that list?
I'm not asking anyone to code this I just don't know how to search for the info I need. I think a list is an array but some answers say an array isn't always a list?
If anyone could tell me the terms I should search for or how to phrase my question to get better answers for each step, I would really appreciate it.
How do I translate these steps into research questions that'll help me learn to do this?
1 How to have player enter some text into a text box 2 how to save that item to a list 3 how to add items to the list 4 Have the computer select an item at random from the list.
Do I even need to use UI right away or can I just fiddle with this in the console and learn the code and learn UI after?
Thank you for your time.
Answer by UnityCoach · Jul 30, 2017 at 05:49 PM
Hi,
I like it that you're asking for the right questions.
So, a List is a wrapper class to handle an array. It's convenient as it allows you to add and remove items from the list. Dictionaries are helpful too, they allow you to find items with a key.
Here's how you declare things:
public string [] someStrings; // an array of strings
public List<string> aListOfStrings = new List<string>(); // a List has to be initialised if it's not serialised
public Dictionary<string, string> aDictionaryOfStrings = new Dictionary<string, string>();
To add to a List, you simply use the Add() method.
aListOfStrings.Add ("hello");
I would start using UI right away, it'll save you the trouble of refactoring things later.
You can add an InputField to your Canvas. InputFields have a OnValueChanged and an EndEdit event you can add your method to. Your method should take a string for parameter.
public void AddTextToList (string text)
{
aListOfStrings.Add (text);
}
Then to randomly select something, you can simply use Random like this :
public string GetRandomText ()
{
return aListOfStrings.[Random (0, aListOfStrings.Count)];
}
Good luck!
Your answer
Follow this Question
Related Questions
How do I get random answers? 2 Answers
How would I implement a random spawn timer into a list based spawn system? 2 Answers
How to Activate Random GameObjects from a list without affecting position 1 Answer
What range of values need to be inserted if we need to pull a random item from the list? 0 Answers