所以我正在设计一个游戏,一旦物体与通电相撞,它应该等待10秒并恢复正常。我正在使用更新函数来保持计数但是一旦使用OnTriggerEnter函数,更新函数就会停止每帧运行。我该如何反击它。请帮忙
public class Powerup_1act : MonoBehaviour {
//This powerup temporarily passes through all lasers
public GameObject EffectiveTo;
private float TimeRemaining;
int flag=0;
float timer=0.0f;
public float alphalevel=.20f;
public GameObject laserfield;
float flag2=0f;
float countdown=0;
void OnTriggerEnter2D(Collider2D other)
{
//Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
if (other.gameObject.CompareTag("Player"))
{
gameObject.SetActive(false);
laserfield.gameObject.tag = "Temp";
flag2 = 1;
changealpha ();
Debug.Log ("Active?"+gameObject.activeInHierarchy);
StartCoroutine(Powerup());
}
}
private IEnumerator Powerup()
{
countdown = 10f;
while (countdown >= 0) {
Debug.Log (timer);
timer += Time.deltaTime;
if (flag2 == 1) {
//changes the alpha level between 0.2f and 0
if (alphalevel > 0 && flag == 0) {
alphalevel -= .05f;
changealpha ();
} else if ((alphalevel == 0 || flag == 1) && alphalevel < .20) {
alphalevel += .05f;
changealpha ();
Debug.Log (alphalevel);
flag = 1;
} else if (alphalevel == .20) {
flag = 0;
}
countdown-=Time.smoothDeltaTime;
yield return null;
}
}
alphalevel = 1f;
changealpha ();
laserfield.gameObject.tag = "Laser";
flag2 = 0;
}
//heres a function to change transparency of player when a powerup is in effect
void changealpha()
{
EffectiveTo.GetComponent<SpriteRenderer> ().color = new Color (1f, 1f, 1f, alphalevel);
}
}
答案 0 :(得分:0)
使用Coroutine
为您带来的好处:
void OnTriggerEnter2D(Collider2D other)
{
StartCoroutine(PowerUp());
}
private IEnumerator PowerUp()
{
countDown = 10f;
while (countDown >= 0)
{
// Logic during the 10 seconds
countDown -= Time.smoothDeltaTime;
yield return null;
}
}
答案 1 :(得分:0)
当您禁用游戏对象时,正在发生的事情是该游戏对象停止运行的脚本。
在您OnTriggerEnter2D
被解雇的情况下,您将游戏对象设置为false gameObject.SetActive(false);
,这意味着此脚本将停止工作,因为您还将此脚本放在游戏对象上刚被禁用。
您应该将OnTriggerEnter2D
事件移动到另一个不被禁用的对象上,您可以从那里禁用此游戏对象。你在Update
中所做的事情也会转移到其他游戏对象。
使GameObject处于非活动状态将禁用所有组件,关闭所有连接的渲染器,对撞机,刚体,脚本等等......例如,您附加到GameObject的任何脚本都将不再调用Update()。 / p>