c# - 检测循环 Unity3D 中最后一个对象的位置
问题描述
下面的脚本在 Y 轴上生成 20 个对象,我怎样才能得到这个循环中最后一个对象的 Y 位置?
脚本:
public GameObject[] Bricks;
void SpawnBricks(int numCubes = 20, float startY = 3, float delta = 0.6f, float AngleDis = 3f)
{
int Rand = Random.Range(0, Bricks.Length);
for (int i = 0; i < numCubes; ++i)
{
var Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
Brick.transform.parent = gameObject.transform;
}
}
解决方案
您只需将声明移到Brick
循环外,以便在循环退出后保留在范围内,并保留循环中分配的最后一个值:
public GameObject[] Bricks;
void SpawnBricks(int numCubes = 20, float startY = 3, float delta = 0.6f, float AngleDis = 3f)
{
GameObject Brick;
int Rand = Random.Range(0, Bricks.Length);
for (int i = 0; i < numCubes; ++i)
{
Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
Brick.transform.parent = gameObject.transform;
}
// Brick now holds the last object returned from Instantiate in the loop
}
推荐阅读
- node.js - 如何使用 UTC,同时使用 prisma.js 和 express.js 项目中的一般定义模型
- r - 来自 R 中 cenGAM tobit1 家族的模型预测超出左右阈值
- google-analytics - 允许贡献者将 Google Analytics 添加到 wiki 页面
- google-apps-script - Google App Script:如何获得 GmailApp 的许可?
- sql - 用于动态查找表、DB2 或 SQL Server 的紧凑 CTE 语法
- sql - 来自现场和 AWS 使用 dacpac-table 的 SQL 复制错误受变更数据捕获控制,无法修改
- java - 用实心圆圈替换按钮?
- flutter - 将 TextFormField 控制器颤动为文本
- typescript - Sonarqube 在 yaml 文件中发现问题,
- azure-devops - Azure Devops 中的 Webhook 禁用没有警报