- Home /
Add all objects of a type to a list before runtime
Hi, I'm making a game which contains many characters, each of which have an opinion of every other character. I want to be able to set each opinion value in the inspector before I press play. To do this I need some kind of list of every character type object that every instance of the the character class can access, but i cant work out how to get each instance to add itself to a list before runtime or even to access a list before pressing play. Is something like this even possible or is there a better way? Thanks in advance for any help.
Answer by goten265 · Jul 04, 2020 at 03:59 PM
Hello tbchicken, so if I am understanding your problem correct you want to have a List visable in the inspector and saved by unity, if so then this is what helped me:
[SerializeField] private List allCharacters = new List();
Now it should be visable in the inspector at script component that this code is in.
Hi, thanks very much for your answer. $$anonymous$$y question was more how would you add/access the elements of a list before runtime or if this is even possible. Do you know how/if this could be done? Thanks again
you could write a editor for your script component and use that to add and remove stuff from the list, to get something from the list you can put in de script a method that returns the character based on the id. of course you could make this easier by making anoher list like the one above and put the names in there then you could do allCharacters[allnames.IndexOf(name)]; then if you put the character and the name on the same id you'd get the character.
public Charater GetCharacter(string characterName) { if (allNames.Contains(characterName)) return allCharacters[allNames.IndexOf(characterName)]; else { Debug.Log($"ERROR: Character {characterName} does not exist."); return null; } }
Ok, I think I'll have a look at that, thanks for you time.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to reference a variable list 2 Answers
Public list are not reflecting in inspector. 1 Answer
Deck Editor 0 Answers