简体   繁体   English

如何在 Unity c# 中声明二维浮点数组?

[英]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.我使用浮点值作为维度,因为我必须在网格的单个单元格中存储多个 pawn。

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.但默认情况下, [,] 的值被视为 int 并且每次我必须将它们类型转换为 int 以检查 if 条件。 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 . C# 中的数组只能按整数类型索引,不能按浮点类型索引 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.如果这是您使用浮点数的唯一原因,那么您可以为每个单元格使用List<PlayerScript> ,并且每个列表可以包含任意数量的PlayerScript

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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