Unity C# 记住 WaitForSeconds Yield之前的变量

本文关键字:变量 Yield 记住 WaitForSeconds Unity | 更新日期: 2023-09-27 18:36:51

我正在尝试生成一个门户位置所在的平台,所以它看起来像是从门户中出来的。

我在这条线上遇到了问题:Vector3 PlatformPosition = m_PortalPosition;,因为SpawnPortal等待 1 秒然后调用 spawn 平台方法,所以m_PortalPosition在分配PlatformPosition时被覆盖。在调用WaitForSeconds(1f);之前,如何"记住"m_PortalPosition的变量?

void Awake()
{       
        for (int i = 0; i < 10; i++)
        {
            StartCoroutine(SpawnPortal());
        }
}
private IEnumerator SpawnPortal()
{
    // Do portal stuff
    // Get an Platform from the object pool.
    GameObject PortalGameObject = m_PortalObjectPool.GetGameObjectFromPool();
    // Generate a position at a distance forward from the camera within a random sphere and put the Platform at that position.
    m_PortalPosition = m_Cam.position + Vector3.forward * m_SpawnZoneDistance + new Vector3(UnityEngine.Random.insideUnitSphere.x * m_PlatFormZoneRadius.x, UnityEngine.Random.insideUnitSphere.y * m_PlatFormZoneRadius.y, UnityEngine.Random.insideUnitSphere.z * m_PlatFormZoneRadius.z);
    PortalGameObject.transform.position = m_PortalPosition;
    yield return new WaitForSeconds(1f);
    SpawnPlatform();
}
private void SpawnPlatform()
{
    // Get an Platform from the object pool.
    GameObject PlatformGameObject = m_PlatformObjectPool.GetGameObjectFromPool();
    //Set the platform position to the portal position, problem with this line
    Vector3 PlatformPosition = m_PortalPosition;
    PlatformGameObject.transform.position = PlatformPosition;
    // Get the Platform component and add it to the collection.
    Platform Platform = PlatformGameObject.GetComponent<Platform>();
    m_platforms.Add(Platform);
    // Subscribe to the Platforms events.
    Platform.OnPlatformRemovalDistance += HandlePlatformRemoval;
    m_lowestPlatformPositionY = m_platforms.Min(x => x.transform.position.y);
}

Unity C# 记住 WaitForSeconds Yield之前的变量

使m_PortalPosition成为SpawnPortal协程中的局部变量,而不是使其成为类变量。每次调用它时,将其作为参数传递给SpawnPlatform,并改用传递的参数。您的代码将更改为:

private IEnumerator SpawnPortal()
{
    //...
    // Note the local variable?
    Vector3 m_PortalPosition = //...
    PortalGameObject.transform.position = m_PortalPosition;
    yield return new WaitForSeconds(1f);
    SpawnPlatform(m_PortalPosition);
}
private void SpawnPlatform(Vector3 PlatformPosition)
{
    //...
    // Commented out, not needed as we are using the argument
    //Vector3 PlatformPosition = m_PortalPosition;
    PlatformGameObject.transform.position = PlatformPosition;
    //...
}

您需要使用局部变量而不是类字段。

这样,对函数的每次调用都将有自己的自变量。