- Home /
how to construct all arrays (classes) with default constructor (not possible)
public PlayerC[] Player = new PlayerC[32]; // 32 since Unity free has max 32 connections
void Start (){
Debug.Log(Player[0].IsEnabled); // gives me null reference Error
Player[0] = new PlayerC();
Debug.Log(Player[0].IsEnabled); // does not give me NRE
for (int i=0; i<Player.Length; i++) {
Player[i] = new PlayerC();
}
}
SO my question is how to make this line:
public PlayerC[] Player = new PlayerC[32];
make all PlayerC class default constructor without making a for loop inside Start() function
thanks in advance
Answer by Jamora · Aug 27, 2013 at 09:05 PM
Any array is initialized with the default value for the type in question. The default value for reference types is null. However, you can get a different default value for value types. If you truly can not loop over your array you must create your Player as a struct and provide whatever default value each should have at initialization.
public struct PlayerC(){
public string name;
public bool IsEnabled;
//provide default values
public PlayerC(){
name = "Empty Player";
IsEnabled = false;
}
}
If you now create an array of Players, each and every Player will have "Empty Player" as its name, and IsEnabled set to false. Thus, you would not get the null reference at line 3.
This of course comes with its down sides, namely that you need to pass them around by reference if you do not want to pass a copy
Answer by roojerry · Aug 27, 2013 at 02:42 PM
Here is a similar question from StackOverflow. What you want is not feasible within the array initializer, but an answer to that question gives a concise solution, though you will probably still have to fill the array from within start, awake or a class constructor
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
C# Class and Array 1 Answer
Array of classes wont set a length c# 1 Answer
how to see class driven out of class in inspector? 1 Answer
Multiple Cars not working 1 Answer