0

When trying to add variables of type CubeDescriptor to an array, I get the error Error: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. I've looked at some other topics on this forum but I can't seem to figure out what I'm doing wrong here.

public class CubeDescriptor
{
    public EcubeType CubeType;
    public Texture2D Texture;
    public bool isMineable;
}

public static CubeDescriptor[] TypeTable = {
                                            {EcubeType.Air, null, false},
                                            {EcubeType.Grass, grass, false},
                                            {EcubeType.Stone, stone, true}
                                           };

2 Answers 2

2
public class CubeDescriptor
{
    public EcubeType CubeType;
    public Texture2D Texture;
    public bool isMineable;
}

public static CubeDescriptor[] TypeTable = new {
                                               new CubeDescriptor(EcubeType.Air, null, false),
                                               new CubeDescriptor(EcubeType.Grass, grass, false),
                                               new CubeDescriptor(EcubeType.Stone, stone, true)

                                           };

EDIT:

If you don't have a constructor then you could do

public static CubeDescriptor[] TypeTable = new {
                                               new CubeDescriptor {CubeType = EcubeType.Air, Texture2D = null, isMineable = false},
                                               new CubeDescriptor {CubeType = EcubeType.Grass, Texture2D = grass, isMineable = false},
                                               new CubeDescriptor {CubeType = EcubeType.Stone, Texture2D = stone, isMineable = true}

                                           };
Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't help at all.
Hmm I just realized I dont even have a constructor for that class
That gives me this error: Cannot initialize type 'Cube_Chaser.Cube2.CubeDescriptor' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
Eh I ended up just making a constructor anyways. Thanks!
2

C# does not support C-style structure initialization.

To fill your array with CubeDescriptor, you need to call the CubeDescriptor constructor to create a new instance.

You can set the field using object initializer syntax:

new CubeDescriptor { CubeType = ..., Texture = ..., ... }

1 Comment

So something like TypeTable[0] = new CubeDescriptor(blah, blah, blah)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.