Home>

### unity - about assigning transform using array

Unity, C # beginner.
Currently, the item random wants to use the position,
"Store random coordinates in the vector array,
Assign it to transform.position of the game object array. "
I was trying to do that, but I just got an error that I couldn't get a reference.

As a method of assigning coordinates,

``````Vevtor3 myPos;
myPos.x = 3.0f;
transform.position = myPos;``````

I think the above method can be the same with an array

``````void Start () {
chest = new GameObject [dropMax];
dropPos = new Vector3 [dropMax];// coordinates
dropRotate = new Quaternion [dropMax];// Placement direction
int i = 0;
while (i&lt;dropMax)
{
dropPos [i] .x = Random.Range (-4.0f, 4.0f);
dropPos [i] .z = Random.Range (-0.5f, 0.5f);
dropRotate [i] .y = Random.Range (-50.0f, 50.0f);
chest [i] .transform.position = dropPos [i];
Chest [i] .transform.rotation = dropRotate [i];
++ i;
}
}``````

I tried as
chest [i] .transform.position = dropPos [i];
chest [i] .transform.rotation = dropRotate [i];
I got an error "NullReferenceException" at

I would like you to teach me about the cause.
In addition, this item is the same type of item, so
I want to place only the positions randomly.

chest [i] because the content of the variable is null.
Attempting to get a null transform will result in a NullReferenceException.

Why chest [i] is null

``chest = new GameObject [dropMax];``

This is because "Create array" is done but "Initialization of array contents" is not done.
Since it has not been initialized, each content of the array is in a state where the default value of GameObject is null.

As a countermeasure

``````chest [i] = new GameObject ();// initialize chest [i]
chest [i] .transform.position = dropPos [i];
chest [i] .transform.rotation = dropRotate [i];``````

It is necessary to put the initialization code of chest [i] like .......