Acess first object in Generic list - C#
Hi, i have a code for shutting down light when button is pressed and lights are inside collider attached to player. But i cant find how to acess first object inside list ? How could I access random object in list ?
Thanks.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LightsOff : MonoBehaviour {
private List<GameObject> ListOfLights = new List<GameObject> ();
private GameObject LLLight;
void OnTriggerEnter (Collider col){
if (col.gameObject.tag == "Player") {
if (gameObject.tag == "Light") {
ListOfLights.Add(LLLight);
LLLight = ListOfLights[0];
}
}
}
void OnTriggerExit (Collider col){
if (col.gameObject.tag == "Player") {
if (gameObject.tag == "Light") {
ListOfLights.Remove(LLLight);
}
}
}
void Update() {
if (Input.GetKeyDown("k")) {
ListOfLights[0].GetComponent<Light>().enabled = false;
}
}
}
@Araw I have having that same error. Did you ever figure it out by any chance?
Answer by g__l · Mar 05, 2016 at 04:51 PM
To access a random object in a list use
ListOfLights[Random.Range(0, ListOfLights.Count)]
To access the first object in a list use
ListOfLights[0]
Ah yes i have already tried those but i keep getting an error argument out of execption..index..thats why i asked the question
Your answer
![](https://koobas.hobune.stream/wayback/20220612070707im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Accessing script from another object 1 Answer
How can I temporary increase the size of an object? 2 Answers
how to change the value of my slider(in the inspector) thanks 0 Answers
Timer wont work 0 Answers