我正在尝试生成一个门户位置正好的平台,所以它看起来像是来自门户网站。
我在使用此行时遇到问题:Vector3 PlatformPosition = m_PortalPosition;
,因为SpawnPortal
等待1秒然后调用spawn platforms方法,m_PortalPosition
会在到达时被覆盖分配PlatformPosition
。
如何在m_PortalPosition
被调用之前“记住”WaitForSeconds(1f);
的变量?
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);
}
答案 0 :(得分:1)
在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;
//...
}
答案 1 :(得分:0)
您需要使用局部变量而不是类字段。
这样,每次调用函数都会有自己的独立变量。