Adding a new string to my array after each button click.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
//This class will be storing words that the
//user enters in to be used.
public class CustomWords : MonoBehaviour {
public Button addword;
public Canvas can;
public InputField wordtext;
public string[] words;
public void Start()
{
addword = addword.GetComponent<Button> ();
can = can.GetComponent<Canvas> ();
wordtext = wordtext.GetComponent<InputField> ();
words = new string[10];
}
public void CustomWord()
{
//with each click of the button it adds the word in the inputfield to the array list.
words[0] = wordtext.text;
}
}
So far so good on this little bit of code that I wrote. I still new to arrays and trying to figure out how to add the word I put in the inputfield to my string array. For example I write the word "The" and click the addword button, it adds that word to the array element 0, now the next time I do it I want it added to the array element 1 and so on till I get to 10. I think I need to use a for loop, but not 100% sure.
Answer by ZefanS · Nov 20, 2015 at 09:15 AM
In order to fill the array from index 0 to 9, simply use a counter that gets incremented on each click / addition to the array.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
//This class will be storing words that the
//user enters in to be used.
public class CustomWords : MonoBehaviour
{
public Button addword;
public Canvas can;
public InputField wordtext;
public string[] words;
public int currentIndex; //This keeps track of the index
public void Start()
{
addword = addword.GetComponent<Button> ();
can = can.GetComponent<Canvas> ();
wordtext = wordtext.GetComponent<InputField> ();
words = new string[10];
currentIndex = 0; //Make sure we start at 0
}
public void CustomWord()
{
//With each click of the button the word in the inputfield is added to the array
words[currentIndex] = wordtext.text; //Add the word at the current index
if (currentIndex < 9)
{
currentIndex++; //Increase the index to the next position in the array
}
else
{
//Change this code to handle the full array
currentIndex = 0; //Reset back to 0 and start filling the array from the start
}
}
}
Currently this just lets the user loop endlessly and keep overwriting the array. You may want to handle things differently when the array is full. To do that, simply change the code in the else statement.
Hope this helps.