Hi there,
I am confusied as to why I get Array Index out of range if I initialise an array in a certain way.
I am trying to display strings on the canvas(inside the text box) from within an array in my script.
When I press the space bar the next string in the array should display.
First of all, I declare the array like so:
public string[] dialogueLines;
Then if I initialise the array, like below, the script does as intended:
void Start () {
dialogueLines = new string[] { "Test 1", "Test 2", "Test 3" };
}
But
if i initialise it like so:
void Start () {
string[] dialogueLines = { "Test 1", "Test 2", "Test 3" };
}
I get the out of range error, despite the console print message showing “Test 1” when it is initialised in Start()
Full code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextController : MonoBehaviour {
public Text dialogueText; // Text that will be written to screen.
public string[] dialogueLines; // String array declaration that will contain the dialogue lines.
public int currentLine = 0; // Tracks the current element position within dialogueLines[].
// Use this for initialization
void Start () {
dialogueLines = new string[] { "Test 1", "Test 2", "Test 3" }; // String array initialisation that contains the dialogue lines.
print("dialogueLines first element on start() : " + dialogueLines[currentLine]);
print("currentLine on start(): " + currentLine);
}
// Update is called once per frame
void Update () {
if (currentLine < dialogueLines.Length)
{
dialogueText.text = dialogueLines[currentLine];
print(dialogueLines[currentLine]);
if (Input.GetKeyDown(KeyCode.Space))
{
currentLine++;
}
}
}
}
Screen shot:
Seems like the array initialised in the second example is lost/destroyed before Update() runs?
Can anyone please explain why this is happening?
Thank you kindly