1

我的拼贴画有一个统一的交通汽车模拟项目,项目要求之一是让用户输入汽车的数量,每辆汽车都应该像AI_Driver一样驾驶,我写了一个脚本来产卵具有实例化功能的汽车,我生成了 1000 辆汽车,当我生成汽车时,我正在进行一些更改,例如(生成的汽车在 y 轴上的位置),

问题是某些汽车已正确编辑,正是我想要的,但其他汽车没有应用位置的更改。

这是脚本:

public class VehicleSpawner : MonoBehaviour
{
    public GameObject[] vehiclePrefabs;
    public int vehiclesToSpawn;
    public bool navON = false;
    public bool aStarON = true;

    void Start()
    {
        StartCoroutine(SpawnMany(0));
    }

    IEnumerator SpawnMany(int count)
    {
        while (count < vehiclesToSpawn)
        {
            GameObject obj = Instantiate(vehiclePrefabs[1]);
            GameObject[] spawningPints = GameObject.FindGameObjectsWithTag("spawningPoint");
            Transform child = spawningPints[Random.Range(0, spawningPints.Length)].transform;

            WaypointNavigator nav = obj.GetComponent<WaypointNavigator>();
            nav.spawner = this;
            nav.priority = Random.Range(0, 2 * vehiclesToSpawn);

            if (!aStarON)
            {
                nav.currentWaypoint = child.GetComponent<Waypoint>();
                nav.navON = navON;
            }
            else
            {
                Transform dest = transform.GetChild(Random.Range(0, transform.childCount - 1));

                nav.start = child.GetComponent<Waypoint>();
                nav.end = dest.GetComponent<Waypoint>();
                nav.priority = Random.Range(0, 10000);
                nav.aStarON = aStarON;
            }

            // change in the position
            obj.transform.position = new Vector3(
                child.GetComponent<Waypoint>().GetPosition().x,
                child.GetComponent<Waypoint>().GetPosition().y + 0.5f,
                child.GetComponent<Waypoint>().GetPosition().z
            );

            yield return new WaitForSeconds(0.05f);

            count++;
        }
    }
}

请问有人可以帮忙吗??

4

1 回答 1

0
  1. Cache spawningPints. Never use Find, because it just runs foreach gameObject in the hierarchy.
  2. Try first to change position, then add Nav component (it might cache position and teleport car back after you change position throw transform).
于 2020-07-26T12:08:39.863 回答