Problem with an array.

When I was using this script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour {

    public GameObject textPrefab;

    public Transform[] spawnPos;

    public float zoomSpeed;

    public Camera camera;

    int count;

    void Awake()
    {
    }

    void Update ()
    {
        camera.fieldOfView -= zoomSpeed/20;
        for (int i = 0; i < spawnPos.Length; i++)
        {
            TextCreate ();
            count += 1;
        }
    }

    void TextCreate ()
    {
        Instantiate (textPrefab, spawnPos[count].gameObject.transform);
    }
}

I would get an ‘IndexOutOfRangeException’ which was causing problems. I searched up this problem and found out I needed to initalize the array.
I did it with this line:

spawnPos = new Transform[spawnPos.Length];

The only problem is that it clears my array and makes it empty, so when TextCreate(); is called, spawnPos[count].gameObject.transform throws an error beacuse the array is empty. What should I do?

Thanks,
Dream

I quickly took some screenshots:
3362074--263357--Screen Shot 2018-01-21 at 08.38.35.png
That’s the full array, which when the game is run becomes this:3362074--263358--Screen Shot 2018-01-21 at 08.38.46.png
Then when TextCreate(); is called I get this error:

Mmmm, bug fixing is so satifying!
Looked around for a while and then realised that ‘IndexOutOfRangeException’ meant it was trying to access an 6th spawn position that didn’t exist.
This is the new code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour {

    public GameObject textPrefab;

    public Transform[] spawnPos;

    public float zoomSpeed;

    public Camera camera;

    int count;

    void Awake()
    {
        count += 0;
    }

    void Update ()
    {
        camera.fieldOfView -= zoomSpeed / 20;
        if (count != 5)
        {
            for (int i = 0; i < spawnPos.Length; i++) {
                TextCreate ();
                count += 1; 
            }
        }

    }

    void TextCreate ()
    {
        Instantiate (textPrefab, spawnPos[count].gameObject.transform);
    }

}

The problem is because your for loop is in the update method and you increase count each time.

Do this instead;

using UnityEngine;

public class Main : MonoBehaviour
{

    public GameObject TextPrefab;

    public Transform[] SpawnPos;

    public float ZoomSpeed;

    public Camera m_camera;

    private void Start()
    {
        for (var i = 0; i < SpawnPos.Length; i++)
        {
            TextCreate(i);        
        }
    }

    private void Update()
    {
        m_camera.fieldOfView -= ZoomSpeed / 20;     
    }

    private void TextCreate(int index)
    {
        Instantiate(TextPrefab, SpawnPos[index].gameObject.transform.position, Quaternion.identity);
    }
}

That works better! Thanks!