禁用GameObject但继续运行Coroutine

时间:2016-02-16 13:43:51

标签: c# unity3d coroutine unity5

我有一个Bonus脚本作为BonusController gameObject的一个组件。这个奖金必须在碰撞时被销毁,但必须&#34;行动&#34;几秒钟我为此启动了一个协同程序,但脚本停止执行(我认为这是因为我将gameObject设置为非活动状态)。以下是void OnTriggerEnter2D(Collider2D col) { StartCoroutine(speedUp(1)); gameObject.SetActive(false); } IEnumerator speedUp(float seconds) { Debug.Log("before"); yield return new WaitForSeconds(seconds); Debug.Log("after"); // <--- This is never called } 的代码:

.container{ /*background-image:url(https://gamepoint.scientificgames.com/sites/busdept/gp/PublishingImages/GP%20site/SG%20Global%20Proposal%20Logo%202015_no%20cube-01.jpg); margin:0px; background-attachment:fixed; background-repeat:no-repeat; background-position:center center; background-image:url(https://gamepoint.scientificgames.com/sites/busdept/gp/PublishingImages/GP%20site/SG%20Global%20Proposal%20Logo%202015_no%20cube-01.jpg); background-size:100% auto; background-repeat:no-repeat; height:100% auto; width:100%; margin:0 auto;*/ border:#5F5F5F thin; }

/*@import url(//fonts.googleapis.com/css?family=Open+Sans);*/ 

.navigation{width:1325px; height:103px;} 

.maincontent{height:955px;} 

.maintable{margin:0 auto; line-height:1px; width:700px;} 

.maintabletext{font-family: &#39;Source Sans Pro&#39;, sans-serif; color:white; font-size:24px; text-align:center;} 

.mainfiller{color:white; font-size:18px; font-family: &#39;Open Sans&#39;, sans-serif; text-align:center; line-height:25px; } 

h1.maintabletext { font-family: &#39;Open Sans&#39;, sans-serif; font-size: 72px; font-weight:700; color:white; text-align:center; }

如何删除对象并且不要停止执行协程脚本?

3 个答案:

答案 0 :(得分:6)

你不能只禁用mesh renderercollider吗?这样游戏对象仍然存在,但用户将无法看到它。

答案 1 :(得分:1)

你无法拉动自己站立的地面。 :)

在使用2D方法时,只需禁用SpriteRenderer即可。并保持对象存活并启用。

{
    StartCoroutine(speedUp(1));
    //gameObject.SetActive (false);
    GetComponent<SpriteRenderer> ().enabled = false;
    GetComponent<Collider2D> ().enabled = false;
    // Above line will deactivate the first collider it will find.
}

IEnumerator speedUp(float seconds)
{
    Debug.Log("before");
    yield return new WaitForSeconds(seconds);
    Debug.Log("after"); // <--- This is never called
}

答案 2 :(得分:0)

为了在一段时间后销毁对象,在yield之后调用coroutine中的destroy。

yield return WaitForSeconds(second);
Destroy(this);

现在它已被正确销毁,并且会释放与仍然在那里相对的内存,看不见但占用资源。