Heðin A. Johansen Heðin A. Johansen - 2 months ago 9
C# Question

C# new array. Class with constructor

I am working in Unity but I guess the same applies to C# in general.

this is a class I made:

public class KeyboardInput
{
private string name;
private KeyCode btn;

public KeyboardInput(string buttonName, KeyCode button)
{
name = buttonName;
btn = button;
}
}


When I create an instance of the class, if I don't specify the values required by the constructor, I will get an error.

Now I want to create an array of the class and I want to specify the values, but how ?

This seems to be working fine without specifying the values

public class InputController
{
private KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];

public InputController()
{
for (int i = 0; i < defaultKeyBinding.Length; i++)
{
//Something inside here
}
}
}


I can tweak the code to be able to set the values inside the for loop, but I am very curious to know if there is a way!

Answer

The line

private KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];

is just declaring an array, nothing is getting initialized yet. In your loop you probably want something like this.

for (int i = 0; i < defaultKeyBinding.Length; i++)
{
    //should look something like this
    defaultKeyBinding[i] = new KeyboardInput("Ayy", KeyCode.A);
}