[英]Unity c# gameobject's override
a和objeler []是游戲對象。我使用yoketme 5次。我得到了一些帶有a的隨機對象,並賦予它們重力。但是,只有1個對象進入bekleme后失去了重力。最后一個a是被所有a覆蓋的對象計時器(9秒)之前使用yoketme的物體。我如何使bekleme拿走所有游戲物體,而不是最后一個?
void YokEtme(){
int x = Random.Range (35, 0);
a = objeler [x];
z = a.GetComponent<Transform> ().position;
a.GetComponent<Rigidbody> ().useGravity = true;
Debug.Log (a);
StartCoroutine (bekleme ());
}
IEnumerator bekleme (){
yield return new WaitForSeconds (9);
a.GetComponent<Rigidbody> ().useGravity = false;
a.GetComponent<Rigidbody> ().constraints = RigidbodyConstraints.FreezePosition;
a.transform.position= z;
a.GetComponent<Rigidbody> ().constraints = RigidbodyConstraints.None;
Debug.Log (a);
}
由於問題中缺少某些上下文,請允許我大膽假設:
a
和z
是MonoBehaviour的字段/屬性。 objeler
隨機選擇五個游戲objeler
,對其施加重力,然后在幾秒鍾后取消施加重力。 如果我的假設是正確的,那么問題就很簡單。 之所以只有一個選定的對象失去重力,是因為Unity一次只允許執行一個協程。
也就是說,即使您調用了YokEtme
,並且每次調用都會導致StartCoroutine(bekleme())
並預期將並行運行五個協程,但實際上,每次調用StartCoroutine(bekleme())
都會丟棄先前運行的協程,並且開始一個新的。
因此,可能的解決方案是在一個協程實例中處理所有五個游戲對象。 如:
using System.Collections.Generic;
using UnityEngine;
public class SomeMono : MonoBehaviour
{
private List<GameObject> _controlledGOs = new List<GameObject>();
private List<float> _loggedZs = new List<float>();
void YokEtme()
{
int x = Random.Range(35, 0);
a = objeler [x];
a.GetComponent<Rigidbody>().useGravity = true;
_controlledGOs.Add(a);
_loggedZs.Add(a.GetComponent<Transform>().position);
}
void SetGravityForGameObjects()
{
for (var i = 0; i < 5; i++)
YokEtme();
StartCoroutine()
}
IEnumerator bekleme ()
{
yield return new WaitForSeconds (9);
for (var i = 0; i < _controlledGOs.Count; i++)
{
var a = _controlledGOs[a];
a.GetComponent<Rigidbody>().useGravity = false;
a.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
a.transform.position= _loggedZs[i];
a.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
Debug.Log (a);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.