- Home /
How to reference a variable list
Hey guys, i don't know if you have a limit of questions per day, sry by posting 2 in the same day, i am just having multiple problems that i can't solve... Anyway, i always use variables in my scripts, but i am making a script that need at least 20 or more, and i am NOT going to make a script that big just for holding the variables, because my script would turn into a book. So, i am using lists (or something like that i don't know the name). It does what i want, it consumes just one line and hold every variable that i want, my question is, how do i reference a variable inside the list?
Let me make myself clear. I have a list named "InstructionSets". Inside the list, there are 3 elements: element 1, element 2, and element 3. How would i reference them on script, separately? Something like this:
public GameObject[] InstructionSets;
void Update()
{
//Your oponent has the golden key, go after him!
GetComponent<NavMeshAgent>().SetDestination(element1.position);
}
Could someone tell me what i need to do? I would be very grateful =)
Answer by roman_sedition · Dec 02, 2016 at 01:19 AM
In your example you have made an array for GameObjects, you should specify the length of the array or you might get an out of bounds error when you try to add to it. Since you have 3 elements you can declare it like this. (Btw you should be using Camelcase for your variables).
public GameObject[] instructionSets = new GameObject[3];
Elements are number from zero onwards, so 3 elements goes from 0 to 2.
this is an example of accessing the third element and then assigning it's position.
instructionsSets[2].transform.position = new Vector3.zero;
If you want to use lists you need to be 'using System.Collections.Generic' and it declare like this.
public List<GameObject> instructionSets = new List<GameObject>();
Like arrays you can access each element like
someList[n] = x;
Or add to the list like.
someList.Add(x);
Where x is the appropriate type.
OH, so i need to use using System.Collections.Generic
and reference them using []
? Okay, thanks, it worked as i expected =)
Could you change your comment to answer?
Answer by Shrikky23 · Dec 02, 2016 at 01:07 AM
When you say reference, do you mean by getting the "Reference" and not "Copy", if so check out ref and out variables in C#.
Or
If you just want to access 1st or 2nd or 3rd element
You can access it like array, make InstructionSets a list and you can still find InstructionSet[0], InstructionSet[1] etc
Use List.Find(type name)
Use List.ElementAt
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to Find all objects with Tag and List their Transforms? 4 Answers
Update list on mouse click 1 Answer
A node in a childnode? 1 Answer