Chris Headleand
Chris Headleand

Reputation: 6193

Creating a 2D array with three data types

In c# what is the best way of creating a 2D array which stores three data types? To create a 2D array I would usually use something like this

public GameObject [][] characters;

But I need to store an int in column 0, a gameObject in column 1 and a float in column 2. Is this possible in c# in unity? or should I be using a different datatype?

Upvotes: 0

Views: 1137

Answers (3)

SimonPJ
SimonPJ

Reputation: 766

How about creating a class to hold these three objects;

class GameData {

    public int IntValue{ get; set; }
    public GameObject gameObject { get; set; }
    public float FloatValue { get; set; }
}

And then using a 1d array to hold them

GameData[] gameData;

You could probably achieve what you are looking for however by creating an object[][] array and using casts on the columns when they are called, but this would not be good practice

Upvotes: 0

Szymon Drosdzol
Szymon Drosdzol

Reputation: 468

You should create a structure (or class) with these threee fields: GameObject, float etc. Then make one dimension array of objects of this structure.

Upvotes: 0

rhughes
rhughes

Reputation: 9583

The best way to do this is to created a class or struct to store your data types, and then create and array of that new object.

It is far easier to encapsulate your different data types into one object. This will help with managing and moving the data around.

For instance:

public class Character
{
    public int MyInt = 0;
    public GameObject MyGameObject = null; // or whatever the default should be
    public float MyFloat = 0.0f;
}

Then create your array:

public Character[] characters;

Upvotes: 2

Related Questions