- Home /
Does C# Support Array of Objects?
I need to do something like following:
public class GameMain : MonoBehaviour {
private Player[] players;
// Use this for initialization void Start () { players[0] = new Player(arenaTexture); players[1] = new Player(arenaTexture); } }
But it returns an error: NullReferenceException: Object reference not set to an instance of an object
Does C# support this? Or is it better if I just use 2 variables: player1 and player2?
Answer by flamy · Jul 16, 2012 at 04:06 AM
public class GameMain : MonoBehaviour{
private Player[] players;
void Start()
{
players = new Player[length/*give the number you need*/];
players[0] = new Player(arenaTexture);
}
}
initialization was the problem you had.... in this case player array is fixed... i usually prefer using Lists because of its flexibility.
using System.Collections.Generic;
public class GameMain : MonoBehaviour{
private List<Player> players;
void Start()
{
players = new List<Player>();
players.Add( new Player(arenaTexture));
}
}
Thank you for your answer. By the way, which is more resource-friendly between the two methods above? And by how much?
hmm generally array are better for defined number of objects and also it is faster than any other method but list are good if u dont knw the size and also it is efficient and easy way of handling stuffs. Also the difference in execution speed is not much.. It purly depends on ur need.
Its close enough to not really matter. List essentially is an array that reallocates it self as needed. If you know how big you will need it, you can set it. Other wise you can remove from and add to as needed.
Unity can serialize Lists, which means you can edit them in the Inspector.
I should explain: List has a property called Capacity, which it uses to reallocated itself as it expands. Example: If you know that you are going to allocate around 1000 objects, but you are not sure,
List<int> myList = new List<int>();
myList.Capacity = 1000;
//Add Your Items
myList.TrimExcess();
if it is 999 it will only reallocated the internal array once.
If it is 1100, it will allocate once then start allocating more as you add.
It is even better to give the inital capacity in the constructor:
List<int> myList = new List<int>(1000);
This prevents the system from reallocating just after the construction, which can sometimes leads to fragmented memory.