- Home /
The question is answered, right answer was accepted
C# Problem with assigning values arrays
i have declared an array:
private int[] ForbiddenKeys;
i have created a function that allows me to add values to the array:
void AddForbidden(KeyCode key)
{
ForbiddenKeys[ForbiddenKeys.Length] = (int)key;
}
and in the start function i call the function:
AddForbidden(KeyCode.Escape);
AddForbidden(KeyCode.CapsLock);
AddForbidden(KeyCode.F1);
AddForbidden(KeyCode.F2);
AddForbidden(KeyCode.F3);
AddForbidden(KeyCode.F4);
AddForbidden(KeyCode.F5);
AddForbidden(KeyCode.F6);
AddForbidden(KeyCode.F7);
AddForbidden(KeyCode.F8);
AddForbidden(KeyCode.F9);
AddForbidden(KeyCode.F10);
AddForbidden(KeyCode.F12);
but unity tell me this:
Assets/Scripts/Menu/Options/Options_Controls.cs(20,23): warning CS0649: Field `Options_Controls.ForbiddenKeys' is never assigned to, and will always have its default value `null'
can anyone help me with this, i have also tried manually assigning the values like this:
ForbiddenKeys[0] = (int)KeyCode.Escape;
Answer by whydoidoit · Jul 13, 2012 at 10:38 PM
You havent initialized the array to a length and you can't set elements unless the array is initialized. You should probably
using System.Collections.Generic;
...
private List<int> forbiddenKeys = new List<int>();
Then add them like this:
forbiddenKeys.Add(KeyCode.F9);
Exactly. An array is an object and therefore a reference type. You have to create an instance of that object to use it. Allso arrays can't change the size! The size have to be specified when you create the array. A List is the best solution in this case.
Also is there a reason why you want to use "int" ? Usually it's better to keep the enum type (which is of course also an int, but it's more typesafe that way).
List<$$anonymous$$eyCode> forbidden$$anonymous$$eys = new List<$$anonymous$$eyCode>();
Follow this Question
Related Questions
Changing a GUI String to read as a INT 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers