- Home /
Add Object to list error (JS).
hi, I am having an error to do with raycasting and adding the object to a list. Here is what I tried:
#pragma strict
var List_1 : Array;
var Object2 : GameObject;
function Start () {
}
function Update () {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, Mathf.Infinity)) {
if(Input.GetMouseButtonDown(0)){
print(hit.collider.gameObject);
Object2 = hit.collider.gameObject;
List_1.Add(Object2);
for(var test in List_1)
{
Debug.Log(test);
}
}
}
}
And the error I am getting is this:
can someone please help, this is really confusing.
It looks like you are trying to use an array as a list when they are different. To add an object to an array you just assign a value to the correct index like List_1[0] = Object2;
If this how it is done in javascript ignore me, I use c#.
And null reference exception means that that object simply is null(empty, not assigned to or not initalized ).
Finally ToString is a function soo place () at the end of it.
Again I may be talking rubbish, but we could help more if the line number from the error matched the script you have provided to allow others to pinpoint what is null.
sorry I didn't mean to put Tosting function in the add section.
The error is on this line:
List_1.Add(Object2);
I am not sure why the error doesn't match, it matchs in monodevelop.
Answer by Eric5h5 · Nov 17, 2014 at 10:46 PM
Never use the JS Array class; use a generic List instead. You need to initialize the list, usually in Awake or Start.
Thank you so much Eric, for anyone else with this problem, here is the code:
#pragma strict
import System.Collections.Generic;
var List_1 : Array;
var Object2 : GameObject;
var myList : List.<GameObject> = new List.<GameObject>();
function Start () {
}
function Update () {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, $$anonymous$$athf.Infinity)) {
if(Input.Get$$anonymous$$ouseButtonDown(0)){
print(hit.collider.gameObject);
Object2 = hit.collider.gameObject;
myList.Add(Object2);
for(var test in myList)
{
Debug.Log(test);
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613171759im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Grab a specific item from a list 3 Answers
Start function on a listed non mono script? 2 Answers
Public list are not reflecting in inspector. 1 Answer
List keeps emptying itself 0 Answers