简体   繁体   中英

How to declare 2D float array in Unity c#?

I am currently working on a game project. I am using float value as a dimension as I have to store multiple pawns in a single cell of a grid.

At some point I have to declare an array location points for selection and movement purpose, so I am using this code to declare

  public PlayerScript[,] Pawns {get; set;}

but by default the value for [,] are taken as int and every time I have to typecast them to int to check the if conditions. And the assignment statement is not working. is it any alternative style to write the same thing to declare the values as float?

Arrays in C# can only be indexed by integer types, not floating point types . This is the norm for most programming languages, and it's not clear what the semantics would be otherwise.

I suggest reconsidering what data structures you're using. You've stated the reason you're wanting to use floats is because you want multiple objects in each cell of the grid. If that's the only reason you're using floats, then you could use a List<PlayerScript> for each cell, and each list could hold any number of PlayerScript s.

public List<PlayerScript>[,] Pawns { get; set; }

You'll need to populate each cell with an empty list object before using it.

Pawns = new List<PlayerScript>[8,8];
for (int r = 0; r < 8; r++)
{
    for (int c = 0; c < 8; c++)
    {
        Pawns[r,c] = new List<PlayerScript();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM