The question is answered, right answer was accepted
Why doesn't the object appear?
I have a "FishStar" object.
I would like to turn it off ("FishStar") for 2 seconds after the collision with the "Player" object and then turn it on again.
I use Coroutine for this.
Where is the mistake?
After adding the script (to "FishStar"), I put the object in the "otherGameObject" tab, but the object after disappearing does not want to appear again.
It's weird because if I add another object instead of otherGameObject tab (in Inspector), it works perfectly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishStarRotation : MonoBehaviour {
public float speed;
private Rigidbody2D rb2D;
public GameObject Bonus;
// Use this for initialization
void Start () {
Bonus = GetComponent<GameObject>() ;
}
// Update is called once per frame
void Update () {
transform.Rotate (0, 0, speed);
}
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.tag == ("Player"))
StartCoroutine ( DIS ());
}
IEnumerator DIS ()
{
Bonus.SetActive(false);
yield return new WaitForSeconds(2f);
Bonus.SetActive(true);
}
}
Answer by polan31 · May 21, 2018 at 10:26 PM
I solved the problem.
Correct working script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishStarRotation : MonoBehaviour {
public float speed;
private Rigidbody2D rb2D;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Rotate (0, 0, speed);
}
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.CompareTag("Player")) {
StartCoroutine (speedUp ());
//gameObject.SetActive (false);
GetComponent<SpriteRenderer> ().enabled = false;
GetComponent<PolygonCollider2D> ().enabled = false;
// Above line will deactivate the first collider it will find.
}
}
IEnumerator speedUp ()
{
Debug.Log("before");
yield return new WaitForSeconds(2f);
Debug.Log("after");
GetComponent<SpriteRenderer> ().enabled = true;
GetComponent<PolygonCollider2D> ().enabled = true;
}
}
Answer by greencheese122 · May 21, 2018 at 12:06 PM
You are disabling the object The script is on,so script stopps running and object don't get enabled Again.Instead of disabling object just disable its collider and renderer with getComponent
Follow this Question
Related Questions
How to force IEnumerator methods to be called only with StartCoroutine 2 Answers
Could not load source 'Coroutines.cs': No source available. 1 Answer
Help with coroutine and IEnumerator on condition 0 Answers
Unity Editor can't find IEnumerated 2 Answers
My code is not working - HELP - IEnumerator Coroutines 0 Answers