- Home /
Question by
jeremy91 · Oct 07, 2013 at 11:32 PM ·
arraylistnullreferenceexceptionadding
List or Array for Rays
How can I write a list or an array and add rays to it within the code? I tried this, but it couldn't add the rays somehow. The console keeps saying (when play pressed) 'NullReferenceExeption: Object reference not set to an instance of an object.' Is there another way to do it?
using System.Collections.Generic;
public List rays;
void Update ()
{
downRay1 = new Ray(transform.position, -Vector3.up);
downRay2 = new Ray (new Vector3 (transform.position.x - 0.5f, transform.position.y, transform.position.z), -Vector3.up);
downRay3 = new Ray (new Vector3 (transform.position.x + 0.5f, transform.position.y, transform.position.z), -Vector3.up);
rays.Add (downRay1);
rays.Add (downRay2);
rays.Add (downRay3);
}
Comment
Best Answer
Answer by aldonaletto · Oct 07, 2013 at 11:43 PM
You must declare the List type (which may have been eaten by the UA formatter), and initialize it:
public List<Ray> rays = new List<Ray>();
void Update ()
{
downRay1 = new Ray(transform.position, -Vector3.up);
downRay2 = new Ray (new Vector3 (transform.position.x - 0.5f, transform.position.y, transform.position.z), -Vector3.up);
downRay3 = new Ray (new Vector3 (transform.position.x + 0.5f, transform.position.y, transform.position.z), -Vector3.up);
rays.Add (downRay1);
rays.Add (downRay2);
rays.Add (downRay3);
}
O$$anonymous$$G, I can't belive the answer was so simple! Now it surely works :) Thanks man!
Your answer
![](https://koobas.hobune.stream/wayback/20220613115512im_/https://answers.unity.com/themes/thub/images/avi.jpg)