Accessing a class within a list
I'm sure this is Unity 101 but I must be missing something really basic...
I have a public class in which I have defined a List. This is in a script which I have added to my main panel using Component>Add>Script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CreateHeroList : MonoBehaviour { [System.Serializable] public class Hero { public string HeroName; public int HeroLevel; public int HeroStars; }
//create a list of Heros as defined above
public List<Hero> Heroes = new List<Hero>();
}
I then have a second script attached tp the same panel in which I am trying to pull data from SQL to populate the Hero class above.
I've tried to create a local instance of the script and access the list from within this:
public CreateHeroList createherolist; createherolist= GetComponent();
I can then access createherolist.Heroes but how do I go one step further to get to createherolist.Heroes.Hero?
Answer by Lysander · Jan 05, 2018 at 01:18 PM
You generally access elements of a collection by using brackets [0] with the index of the element you want to retrieve inside, like CreateHeroList.Heroes[0] (but be sure to check it has at least that many elements first, with the .Length property), or by iterating over the entire collection one element at a time with a "for" loop or "foreach" loop. I recommend reading this for information on arrays, and this for information on lists (lists mostly work like arrays, but can be dynamically resized and re-ordered).