数组 C# 错误 Unity3D
本文关键字:Unity3D 错误 数组 | 更新日期: 2023-09-27 18:36:24
我正在尝试将此代码从 Js 转换为 C#,但我遇到了一些麻烦。该代码是关于使用数组创建一个新娘。这是脚本,在Unityscript中工作正常:
var levelArray : int[,]; var levelSize : Vector2 = new Vector2(19,13);
var steelblock : Transform;
function Start ()
{
SetupLevel();
}
function SetupLevel()
{
levelSize.x = Mathf.FloorToInt( levelSize.x );
levelSize.y = Mathf.FloorToInt( levelSize.y );
levelArray = new int[ levelSize.x, levelSize.y];
var block : Transform;
for( var y : int = 0; y < levelSize.y ; y++)
{
for(var x : int = 0 ; x < levelSize.x ; x++)
{
if(x == 0 || x == levelSize.x - 1 ||y ==0 || y == levelSize.y -1)
{
levelArray[ x , y ] = 2;
block = Instantiate(steelblock,Vector3(x,y,0), Quaternion.identity);
block.name = "steel_"+x.ToString() + "_"+ y.ToString();
block.parent = transform;
}
else if(x% 2 == 0 && y %2 ==0)
{
levelArray[ x , y ] = 2;
block = Instantiate(steelblock,Vector3(x,y,0), Quaternion.identity);
block.name = "steel_"+x.ToString() + "_"+ y.ToString();
block.parent = transform;
}
}
}
}
尝试将此代码从 Javascript 转换为 C#,但我遇到了一些错误。
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour
{
int[,] levelArray ;
Vector2 levelSize = new Vector2(19,13);
Transform steelblock;
// Use this for initialization
void Start ()
{
SetupLevel ();
}
void SetupLevel()
{
levelSize.x = Mathf.FloorToInt( levelSize.x );
levelSize.y = Mathf.FloorToInt( levelSize.y );
levelArray = new int[ levelSize.x, levelSize.y];
Transform block ;
for( int y = 0; y < levelSize.y ; y++)
{
for(int x = 0 ; x < levelSize.x ; x++)
{
if(x == 0 || x == levelSize.x - 1 ||y ==0 || y == levelSize.y -1)
{
levelArray[ x , y ] = 2;
block = Instantiate(steelblock,new Vector3(x,y,0), Quaternion.identity);
block.name = "steel_"+x.ToString() + "_"+ y.ToString();
block.parent = transform;
}
else if(x% 2 == 0 && y %2 ==0)
{
levelArray[ x , y ] = 2;
block = Instantiate(steelblock,new Vector3(x,y,0), Quaternion.identity);
block.name = "steel_"+x.ToString() + "_"+ y.ToString();
block.parent = transform;
}
}
}
}
}
错误位于以下行中:
levelArray = new int[ levelSize.x, levelSize.y];
它告诉我"无法隐式将类型浮点数'转换为 int'。存在显式转换(您是否缺少强制转换?
block = Instantiate(steelblock,new Vector3(x,y,0), Quaternion.identity);
它告诉我"无法隐式地将类型UnityEngine.Object'转换为UnityEngine.Transform"。存在显式转换(您是否缺少强制转换?
你能帮忙吗?
提前致谢
编译器错误消息确实告诉您出了什么问题:levelSize 的类型是 Vector2
。属性 X
和 Y
的类型为 float
,而不是 int
。另一个问题是类似的类型:编译器无法转换不同的UnityEngine
类型,因此您需要自己执行此操作。
将特定代码行更改为如下所示的内容。这不是最好的方法,也没有测试过,但它可能会起作用:
levelArray = new int[Convert.ToInt32(levelSize.x), Convert.ToInt32(levelSize.y)];
和
block = Instantiate(steelblock as UnityEngine.Transform, new Vector3(x,y,0), Quaternion.identity);