Question by
RIjaz · Nov 08, 2019 at 04:43 AM ·
gameobjectnullreferenceexceptionpositioning
Changing positions of all GameObjects in an array
I am constantly getting a Null Reference error when I try to change the positions of the game objects stored in an array. This is my current code:
public class Trader : MonoBehaviour
{
private GameObject[] traders = new GameObject[9];
private Vector3[] positions = new Vector3[9];
void Start()
{
for (int i = 1; i < 9; i++)
{
GameObject pos = GameObject.Find("Wall"+i);
GameObject trader = GameObject.Find("Trader" + i);
this.positions[i] = pos.transform.position;
this.traders[i] = trader;
}
}
// Update is called once per frame
void Update()
{
SetPositions();
}
private void SetPositions()
{
int randPos;
bool[] assigned = new bool[8];
int count = 0;
while (count < 8)
{
randPos = Random.Range(0, 8);
if (!assigned[randPos])
{
//error occurs here
this.traders[count].transform.position += this.positions[randPos] - new Vector3(0f, 0f, 1f);
assigned[randPos] = true;
count++;
}
else
{
continue;
}
}
}
}
Comment