Lists and dictionaries
Scripts can keep a growing list of things, or look things up by a key, with C#'s List<T> and
Dictionary<TKey, TValue>. Add using System.Collections.Generic; at the top of the script.
private List<string> bag = new List<string>();
private Dictionary<string, int> scores = new Dictionary<string, int>();
public override void Interact()
{
bag.Add("Gem");
string me = Networking.LocalPlayer.displayName;
scores.TryGetValue(me, out int score);
scores[me] = score + 5;
foreach (var entry in scores) Debug.Log(entry.Key + ": " + entry.Value);
}
What you can store: numbers, bool, enums, Vector2/3/4, Quaternion, Color, strings, arrays, objects
(GameObjects, components), players, other scripts, and other lists or dictionaries. Dictionary keys can be int, an
enum or string.
| Members | |
|---|---|
List<T> | Count, list[i], Add, Insert, Remove, RemoveAt, Clear, Contains, IndexOf, Sort() (numbers, enums and strings), Reverse(), ToArray(), foreach, and new List<int> { 1, 2, 3 } |
Dictionary<TKey, TValue> | Count, dict[key], Add, Remove, ContainsKey, Clear, TryGetValue, foreach (var kv in dict) with kv.Key and kv.Value, and foreach over dict.Keys or dict.Values |
Mistakes that stop the script
Like an array index out of range, these stop the script with an error in the console:
- reading a list index that does not exist;
- reading a dictionary key that is not there (use
TryGetValueorContainsKeyfirst); Addwith a key that already exists;- a
nullstring key; - adding or removing items while a
foreachwalks the same collection. Changing a value in a dictionary is fine.
Limits
- Up to 65,536 items in one list or dictionary, and up to 262,144 items across all the collections one script keeps.
- Collection types can nest up to 8 levels deep (for example
List<Dictionary<string, int[]>>is 3). - Collections are not shown in the Inspector. A
List<T>of synced types can be shared with[Synced, MaxLength(n)](Add,Insert,RemoveAt,Clear,Count,[i]andforeach); dictionaries can't be synced. - Not available:
HashSet,Queue,Stack, LINQ,AddRange,Find, sorting with your own comparison, and lists ofobject.
See the Inventory example.