- Home /
Assign collider and linerenderer to list
I'm trying to assign the LineRenderer and the CapsuleCollider from each object to a list, I get: NullReferenceException: Object reference not set to an instance of an object and: Is never assigned to and will always have it's default value null
I've looked at similar questions but still can't wrap my head around why this isn't working
public List<GameObject> lasers;
List<LineRenderer> laserLines;
List<CapsuleCollider> capsules;
void Awake()
{
for (int i = 0; i < lasers.Count; i++) {
startPoint[i] = lasers[i].transform;
Debug.Log(lasers[i]); //lasers are fine
laserLines[i] = lasers[i].GetComponent<LineRenderer>();
capsules[i] = lasers[i].GetComponent<CapsuleCollider>();
capsules[i].radius = 5.5f / 2;
capsules[i].center = Vector3.zero;
capsules[i].direction = 2; // Z-axis for easier "LookAt" orientation
}
}
your code seems fine. but did you assign values to lasers list. and if you assigned did laser gameobjects have linerenderer and capsile collider attached?
Answer by ShadyProductions · Jul 26, 2017 at 11:24 AM
are your lists initialized?
List<LineRenderer> laserLines = new List<LineRenderer>();
List<CapsuleCollider> capsules = new List<LineRenderer>();
Note that you should use laserLines.Add(line); and capsules.Add(capsule); and not access them by index. If you do want to access index like you are doing now then maybe its better to use an array for this the way you are trying to do it like so:
LineRenderer[] laserLines;
CapsuleCollider[] capsules;
void Awake()
{
laserLines = new LineRenderer[lasers.Count];
capsules = new CapsuleCollider[lasers.Count];
for (int i = 0; i < lasers.Count; i++) {
startPoint[i] = lasers[i].transform;
Debug.Log(lasers[i]); //lasers are fine
laserLines[i] = lasers[i].GetComponent<LineRenderer>();
capsules[i] = lasers[i].GetComponent<CapsuleCollider>();
capsules[i].radius = 5.5f / 2;
capsules[i].center = Vector3.zero;
capsules[i].direction = 2; // Z-axis for easier "LookAt" orientation
}
}