- Home /
String array not working
ive been watching a tutorial on making inventory systems in unity but I cant figure out why this one bit keeps on giving me errors in the tutorial (https://youtu.be/3RW3FgIFYSU?t=166) he tells us to create a string array in his version in the [] brackets he has no number but mine gives me errors because of this and when I put the right number in (9) it gives me the error Expression denotes a value', where a `method group' was expected
I cant see what he did clearly in the video because of the crappy quality, and the source code is not updated to this episode
heres my code string[] names = new string[9]("Grass", "Dirt", "Stone", "Dry Sand", "Wet Sand", "Coal", "Iron", "Gold", "Diamond" );
When you actually set the video quality to 1080p and go full screen it can be seen pretty clear. Here's a screenshot:
Answer by SohailBukhari · Jul 14, 2017 at 10:00 AM
basically this repenting the array size you don't need to initialize
string[] names= { "Grass", "Dirt", "Stone", "Dry Sand", "Wet Sand", "Coal", "Iron", "Gold", "Diamond"};
Edit: Thanks to @Bunny83
The problem is that you used normal brackets "( )" instead of curly brackets " { }" for the initialization block.
For classes, for example String, it's the same:
String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};
You are right with your example but the array size is not the problem. The problem is that he used normal brackets "( )" ins$$anonymous$$d of curly brackets " { }" for the initialization block.
This does work just fine:
string[] myStringArray = new string[3]{"a","b","c"};
However you have to make sure you supply the same number of initialization values as the array size specifies. So new string[4]{"a","b","c"};
or new string[2]{"a","b","c"};
would cause a compilation error. In most cases you would omit the array size because it's easier to extend the array because you don't have to take care of the size as well. However in some cases it might be useful when the array must have a certain size so a programmer (doesn't have to be you) doesn't accidentally add or remove elements.
ps: $$anonymous$$eep in $$anonymous$$d that the short initialization method:
string[] myStringArray = {"a","b","c"};
does only work when used directly in a field initializer / variable initialization. In all other cases this does not work
string[] array;
array = {"a","b","c"}; // <<-- error
array = new string[]{"a","b","c"}; // <<-- correct
void Test(string[] arr)
{
}
Test({"a","b","c"}); // <<-- error
Test(new string[]{"a","b","c"}); // <<-- correct
Your answer
Follow this Question
Related Questions
Access all Items in an Array 4 Answers
how to randomly pick a string from an array 3 Answers
Convert Array into One String (Js) 1 Answer
how to get game object by string? 0 Answers
Extending the Array class? 1 Answer