它返回您要问的
我有2个对象:
- 瓷砖:只有一个矩形平面
- 条纹:瓷砖的集合
在GameManager脚本中,我每2秒实例化条纹,在条纹脚本中,我会使用随机数进行循环插入瓷砖,并且我正在将它们育儿到刚刚创建的条纹。
。我的问题是我想找出每个实例化条纹的瓷砖的数字吗?
我的意思是使用 newStripe.transform.childCount
无法正常工作,因为它总是会返回零,而仅出于测试原因,我通过添加一个空游戏对象编辑了条纹预制,然后应用更改newStripe.transform.childCount
将返回1。
我知道我应该在这种情况下使用对象合并技术,但是我是一个初学者,我正在尝试学习。
// GameManager Script
void Update()
{
timeBetweenSpawns -= Time.deltaTime;
if (timeBetweenSpawns < -2)
{
Stripe newStripe = Instantiate(stripePrefab, spawnPosition,
Quaternion.identity);
// This variable (tilesCountIntStripe) always returns zero
tilesCountInStripe = newStripe.transform.childCount;
timeBetweenSpawns = 0;
}
}
// Stripe Script
void Update()
{
if (createTile)
{
int randomStripesCount = Random.Range(1, 10);
for (int i = 0; i < randomStripesCount; i++)
{
Tile newTile = Instantiate(tile);
newTile.transform.SetParent(transform, true);
newTile.transform.localPosition = new Vector2(transform.position.x, (-i * (1.1f)));
tilesCount += 1;
}
createTile = false;
}
}
它返回您要问的0
,因为Tile::Update()
尚未运行
如果您希望该代码立即运行,我建议这样做这样的事情:
// GameManager Script
void Update()
{
timeBetweenSpawns -= Time.deltaTime;
if (timeBetweenSpawns < -2)
{
Stripe newStripe = Instantiate(stripePrefab, spawnPosition,
Quaternion.identity);
tilesCountInStripe = newStripe.GetComponent<Stripe>().Init();
//Or whatever the exact name of your class is ^ here
timeBetweenSpawns = 0;
}
}
// Stripe Script
public int Init()
{
int randomStripesCount = Random.Range(1, 10);
for (int i = 0; i < randomStripesCount; i++)
{
Tile newTile = Instantiate(tile);
newTile.transform.SetParent(transform, true);
newTile.transform.localPosition = new Vector2(transform.position.x, (-i * (1.1f)));
tilesCount += 1;
}
return randomStripesCount;
}
更改:
- 我们没有等待更新来创建图块,而是将它们实例化,以您控制的代码调用的
Init
函数。- 这还删除了具有防止更新代码(帧运行一次(运行每个帧的
createTile
字段的必要性。- 这应该是您在错误的地方做事的线索
- 这还删除了具有防止更新代码(帧运行一次(运行每个帧的
- 从此初始方法(快速(返回随机数的瓷砖,避免查询转换层次结构(慢(。