Kārlis Kauliņš
Kārlis Kauliņš

Reputation: 21

error CS0847: An array initializer of length '120' is expected

I am trying to compare elements of array to variables, but I always get this error and I don't know what to do to fix it.

using System;
using System.Linq;

public string[] groups = new string[120] { "hydrogenScreen" , "heliumScreen", "menu", "li", "be", "b", "c", "n", "o", "f", "ne", "na", "mg", "al", "si", "p", "s", "cl", "ar", "k", "ca","sc", "ti","v", "cr","mn","fe","co", "ni", "cu", "zn", "ga", "ge", "as", "se", "br", "kr", "rb", "sr", "y" , "zr", "nb", "mo", "tc", "ru" , "rh", "pd", "ag", "cd", "in" , "sn", "sb" , "te", "i", "xe", "cs", "ba", "la", "ce", "pr", "nd", "pm", "sm", "eu", "gd", "tb", "dy", "ho", "er", "tm", "yb", "hf", "ta", "w", "re", "os", "ir", "pt", "au", "hg", "tl", "pb", "bi", "po", "at", "rn", "fr", "ra", "ac", "th", "pa", "u", "np", "pu", "am", "cm", "bk", "cf", "es", "fm", "md", "no", "lr", "rf", "db", "sg", "bh", "hs", "mt", "ds", "rg", "cn", "nh", "fl", "mc", "lv", "ts", "og" };

public void efficientTabChange(CanvasGroup group, string groups)
{
    
    for (int n = 0; n < 119; n++)
    {
        string check;
        check = group.ToString();
        string check1 = groups[n].ToString();
        if (check.Equals(check1))
        {
            ActivateTabs(group);
        }
        else
        {
            DeactivateTabs(group);
        }

    }
}

It is for button in unity to change tabs, but when I click it also gives me error for index being out of bounds

Upvotes: 0

Views: 61

Answers (1)

Fildor
Fildor

Reputation: 16129

The error suggests your initializing has not enough elements. I didn't count them but you should.

You either want 119 elements, then it should be new string[119] or you want 120, then you need another element.

You can also omit the length if you initialize like that:

string[] groups = { ... }; // the dots would be your elements, of course
// or 
var groups = new string[] { ... }; 

or (given that syntax is available in your version of Unity)

string[] groups = [ ... ]; // again the dots are your elements

See Fiddle: https://dotnetfiddle.net/oRgYiq


Additionally (but not the cause for the error):

Replace that 119 with for (int n = 0; n < groups.Length; n++).

That way you can later change that array's length without touching that loop again. It also automatically gives you the correct upper bound. (You are one off)

To be clear: with n < 119, the biggest n will be 118. So it's a "one-off" mistake.

For your reference : https://learn.microsoft.com/en-us/dotnet/api/system.array.length?view=net-9.0

Upvotes: 3

Related Questions