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);
}
A coroutine will not continue to run if the game object is disabled. You must run the coroutine from another game object, or in some situations you can disable rendering instead.
Side note about this line:
if (coll.gameObject.tag == ("Player"))
You needn’t put the (“Player”) written like that. I mean, you can, but it’s not necessary.
That being said, it’s better to use:
void OnCollisionEnter2D(Collision2D coll){
Debug.Log("I hit " + coll.name);
if (coll.gameObject.CompareTag("Player")) //or the tag name of what ever you collided with
{
StartCoroutine ( DIS ());
}
}
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;
}
}
You said you need two objects… so is “Player” the child? That could be one reason.
If the parent and child are both named “Player”, the line of code doesn’t do both.
Rather than guessing more, if you explained a bit more, it might help.
Also note, that while line with ‘Find’ works, you could create a reference for the child sprite renderer and use that, instead. That is good practice. Say you renamed the game object, it would continue to work. Even if that doesn’t seem likely to you right now. =)