I would really like to know if anybody knows how to hide and show gameobjects in unity 5, either by disabling and re-enabling it after 4secs, or even by someother method that I have not heard of yet. At the moment my gameobject being a coin works great when the player collides it collects the coin and adds a point to my score system, but I have written the code to destroy the gameobject once triggered because I do not know how to hide it temporarily, so if anyone knows how to do this please do share because I really need to know asap my code is visible below for you all to analyse the problem is on line 15 the Destroy (gameObject); is down the bottom.
using UnityEngine;
using System.Collections;
public class CoinPickUp : MonoBehaviour {
public int pointsToAdd;
void OnTriggerEnter2D (Collider2D other)
{
if (other.GetComponent<LopterMovement> () == null)
return;
ScoreManager.AddPoints (pointsToAdd);
Destroy (gameObject);
}
}
You can use the statement below to instead of destroying it. That will simply “hide” it from being active in the scene.
gameObject.SetActive(false);
You might also want to think about pooling for objects such as coins and other prefabs that are instantiated multiple times. You can search the asset store for “pooling” to save you the time of coding it yourself.
considering you want to reactivate it later, i would set the rigidbody and the renderer to be disabled, then invoke a function to reactivate them.
code below was not spellchecked or checked for proper setup. but the idea is there so it shouldnt be too hard to find the functions/properties/classes needed to make it work.
using UnityEngine;
using System.Collections;
public class CoinPickUp : MonoBehaviour {
public int pointsToAdd;
SpriteRenderer rend;
Rigidbody2D rb2;
void start(){
rend = gameObject.GetComponent<SpriteRenderer>();
rb2 = gameObject.GetComponent<RigidBody2D>();
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.GetComponent<LopterMovement> () == null)
return;
ScoreManager.AddPoints (pointsToAdd);
rb2.enabled = false;
rend.enabled = false;
invoke(Enabler,4f);
}
void Enabler(){
rb2.enabled = true;
rend.enabled = true;
}
}