using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateStairs : MonoBehaviour
{
[Header("Stairs Prefb")]
public GameObject stairsPrefab;
[Space(5)]
[Header("Platforms")]
public bool addPlatforms = false;
public GameObject platformsPrefab;
[Space(5)]
[Header("Settings")]
[Range(1, 20)]
public int numberOfUnits = 1;
public float delay = 3;
public int stairsNumber = 5;
public Vector3 stairsStartPosition;
public Vector3 stairSize;
public Vector3 stairsSize;
public float stepWidthFactor = 1f;
private Vector3 stairsPosition;
private GameObject stairsParent;
private int oldNumberOfUnits = 0;
// Use this for initialization
void Start()
{
oldNumberOfUnits = numberOfUnits;
for (int i = 0; i < numberOfUnits; i++)
{
stairsParent = new GameObject();
stairsParent.name = "Stairs";
StartCoroutine(BuildStairs());
}
}
// Update is called once per frame
void Update()
{
if(oldNumberOfUnits != numberOfUnits)
{
StartCoroutine(BuildStairs());
oldNumberOfUnits = numberOfUnits;
}
}
private IEnumerator BuildStairs()
{
for (int i = 1; i <= stairsNumber; i++)
{
stairsPosition = new Vector3(
stairsStartPosition.x,
stairsStartPosition.y + (i * stairsSize.y),
stairsStartPosition.z + (i * stairsSize.y) * stepWidthFactor);
GameObject stair = Instantiate(
stairsPrefab,
stairsPosition,
Quaternion.identity);
stair.tag = "Stair";
stair.transform.parent = stairsParent.transform;
stair.transform.localScale = stairSize;
yield return new WaitForSeconds(delay);
}
stairsParent.AddComponent<MoveObjects>().Init();
}
}
在“开始”中,我正在执行一个循环,然后根据numberOfunits启动协程。
如果numberOfUnits为1,则工作正常。但是例如2大于1,它首先创建第一组楼梯,但是在第二个“楼梯”父级上,它仅创建1个楼梯。我不想让它等待完成我想要的第一个协程,以创建多个协程的楼梯。
我还想在每个楼梯单元之间添加一个间隙。 并且如果要在Update中进行更改,如果我更改numberOfUnits,它将添加/销毁更多的楼梯单位。所有楼梯单位都应在StartCoroutine中实例化。
答案 0 :(得分:2)
您误会了协程的工作方式而不是线程。发生的情况是您不断调用协程,因此它会一遍又一遍地创建而不创建单独的实例。
您应该做的是创建一个预制件,并将其实例化以完成工作。我的最后一句话是关于线程的,但是除非将其实例化在主线程上,否则您将无法实例化任何东西,因此最简单的方法就是这样。
String daughterName = reader.readLine();
Cat catDaughter = new Cat(daughterName, catMother);
您之前的课程将删除此
public GameObject yourGoWithAboveClassOnIt;
void Start()
{
oldNumberOfUnits = numberOfUnits;
for (int i = 0; i < numberOfUnits; i++)
{
Instantiate(yourGoWithAboveClassOnIt);
}
}