C# Transform array problem

So i’ve been trying to figure out why this code causes a runtime NullReferenceException when it executes the “viewPoints[0].position =” line below.

If i use a two Vector3 arrays (one for pos, one for rot) instead of a Transform i can get it to work, but i wanted to use a Transform.

Any ideas on what is wrong?

Thanks


Transform[ ] viewPoints;

viewPoints = new Transform[10];
if (viewPoints != null) {
viewPoints[0].position = new Vector3(34.0f, 5.0f, -33.0f);
viewPoints[0].eulerAngles = new Vector3(348.0f, 350.0f, 0.0f);
}

did you ever initiate all the array slots?

just creating the array will not create valid entries, it will only reserve the memory for the array. its content is still null

It’s a common mistake to assume that Transforms can be used as temporary objects to store position, rotation and scale data. They’re actually Components, which means that they can only exist if they’re attached to a GameObject, so in order to make an array of Transforms you also have to create a bunch of GameObjects and put references to their Transforms into the array. This is probably not what you really want.

Instead, either make separate arrays for position and rotation, as you’ve already described, or make a custom non-MonoBehaviour class that has members for position and rotation, then make an array of that custom class. In C#, you probably also want to write [System.Serializable] before the class declaration so that it can be displayed in the inspector.

I actually figured this out. I ended up creating a struct with a couple of Vector3s for position and rotation and used that instead. Thanks for the heads up.