I want to create a list of horses and print the name of the Horses that are stored in the list. Although I got the answer correct as I desired, there's one thing that is puzzling me when I declare a list variable.
I declared it as:
public List<string> myFavouriteHorses;
and in an example I have seen it's declared like this:
public List<string> myFavouriteHorses = new List<string> ();
Despite this difference, both of them worked. What's the difference between these two approaches? Does it matter which one I use?
Here's the entire code which i tried:
using UnityEngine;
using System.Collections.Generic;
public class LearningScript : MonoBehaviour {
public List<string> myFavouriteHorses = new List<string> ();
void Start(){
myHorses ();
}
void Update(){
if (Input.GetKeyDown (KeyCode.Return)) {
Print ();
}
}
void myHorses(){
myFavouriteHorses.Add ("Grey Horse");
myFavouriteHorses.Add ("Black Horse");
myFavouriteHorses.Add ("Rudolph Horse");
myFavouriteHorses.Add ("Biting Horse");
}
void Print(){
Debug.Log ("This list has " + myFavouriteHorses.Count + " horses");
Debug.Log ("The horse at index 1 is " + myFavouriteHorses [1]);
Debug.Log ("The horse at index 2 is " + myFavouriteHorses [2]);
Debug.Log ("The horse at index 3 is" + myFavouriteHorses [3]);
}
}
Here's the output
Why doesn't it make a difference whether or not I initialize the List
with new
before using it?