Whats wrong with this simple code?
using UnityEngine;
using System.Collections;
public class RemovableObject : MonoBehaviour
{
void OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "RemovableObject")
{
col.gameObject.SetActive (false);
yield return new WaitForSeconds (5);
col.gameObject.SetActive (true);
}
}
}
I don't understand why this simple script returns an error... the error is:
Assets/RemovableObject.cs(6,14): error CS1624: The body of `RemovableObject.OnCollisionEnter(UnityEngine.Collision)' cannot be an iterator block because "void" is not an iterator interface type'
Answer by Taxen0 · Feb 05, 2016 at 02:56 PM
A coroutine should always return IEnumerator (not void as in your case). Try to use something like this:
using UnityEngine;
using System.Collections;
public class RemovableObject : MonoBehaviour
{
void OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "RemovableObject")
{
DeactivateObject(col.gameObject);
}
}
IEnumerator DeactivateObject(gameObject obj)
{
obj.SetActive (false);
yield return new WaitForSeconds(5);
obj.SetActive (true);
}
}
Thanks, this worked: IEnumerator OnCollisionEnter (Collision col) { %|-2045180173_1|% %|-981860038_2|% %|1730326008_3|% %|1732409442_4|% col.gameObject.SetActive (true); %|-1368844139_6|% }
And code on this website is fu*ked..
IEnumerator OnCollisionEnter (Collision col) { if(col.gameObject.tag == 'RemovableObject') { col.gameObject.SetActive (false); yield return new WaitForSeconds (5); col.gameObject.SetActive (true);
}
}
nice work! here is the code in case anyone else wants to read it (you need to have 4 spaces in front of each line)
IEnumerator OnCollisionEnter (Collision col) {
if(col.gameObject.tag == 'RemovableObject') {
col.gameObject.SetActive (false);
yield return new WaitForSeconds (5);
col.gameObject.SetActive (true);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612063117im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why is my Rigidbody freaking out like this? 0 Answers
Getting a variable timed Interval with coroutine and yield? 0 Answers
OnCollisionEnter Trigger 1 Answer
OnCollisionEnter - Enabled C# 1 Answer
Why isn't WaitForSeconds working? 1 Answer