I am a total newbie and have a idea for game that I would like to try.
It is a word game, and I want to let a user click on a series of letters, each letter will need to have a score and character constant. These letter game objects need to be stored until a button is pressed to submit the current word.
So I need a place to store the score and character for each letter. For this I thought I would have to attach a script to each letter prefab and that stores the constants.
For the collection of letters I was thinking of using a built in array of gameobjects. Is this the best option? Is will I be able to resize the array as gameobjects are added and removed?
Thanks.
I would use a list instead of an array. Arrays cannot be resized without a new one being created, while lists can have items added or removed.
Letter.cs
using UnityEngine;
public class Letter : MonoBehaviour
{
public char character = 'a';
public int score = 1;
}
Test.cs
using UnityEngine;
using System.Collections.Generic; // lets you use Lists
public class Test : MonoBehaviour
{
public List<Letter> letters = new List<Letter>(); // letters can be set in the inspector
void Start()
{
// make sure list is not null
if (letters == null)
letters = new List<Letter>();
Letter let = GetComponent<Letter>();
letters.Add(let); // add a Letter to the end of the list
for (int i = 0; i < letters.Count; ++i) // loop through each letter in the list
{
Letter letter = letters*;*
foreach (Letter letter in letters) // loop through each letter in the list
{
// …
}
letters.RemoveAt(0); // remove the very first letter in the list