Hello, i have read that creating and destroying many object is bad for games on mobile phone. So i decided to use pooling. but now my script is not working:
object is not “destroyed”, when it leaves camera sight, it destroyes after 6 seconds. Why is that?
public class CloudMovement : MonoBehaviour
{
public Vector2 speed = new Vector2();
public Vector2 direction = new Vector2();
private Vector2 movement;
private bool hasSpawn;
void OnEnable(){
if (!gameObject.renderer.isVisible) {
print("you see me");
Invoke ("Destroy", 6f);
}
}
void Destroy(){
gameObject.SetActive (false);
}
void OnDisable(){
CancelInvoke ();
}
void Update(){
movement = new Vector2(
speed.x * direction.x,
speed.y * direction.y);
}
void FixedUpdate(){
rigidbody2D.velocity = movement;
}
}
Other scipt
public class CloudPool : MonoBehaviour {
public GameObject cloud;
public GameObject shape;
public int pooledAmount = 20;
List<GameObject> clouds;
List<GameObject> shapes;
// Use this for initialization
void Start () {
shapes = new List<GameObject> ();
for (int i = 0; i<pooledAmount; i++) {
GameObject obj = (GameObject)Instantiate(shape, new Vector3(Random.Range(-15, 15), Random.Range(-9, -5), 0), Quaternion.identity);
shapes.Add(obj);
}
clouds = new List<GameObject> ();
for (int i = 0; i<1; i++) {
GameObject objS = (GameObject)Instantiate(cloud, new Vector3(Random.Range(-37, -16), Random.Range(5, 15), 0), Quaternion.identity);
clouds.Add(objS);
}
}
// Update is called once per frame
void Update () {
for (int i = 0; i<clouds.Count; i++) {
if(!clouds*.activeInHierarchy){*
_ clouds*.transform.position = new Vector3(Random.Range(-0, -16), Random.Range(5, 15), 0);_
_ clouds.SetActive(true);
break;
}
}*_
* for (int i = 0; i<shapes.Count; i++) {*
_ if(!shapes*.activeInHierarchy){
shapes.transform.position = new Vector3(Random.Range(-15, 15), Random.Range(-9, -5), 0);
shapes.SetActive(true);
break;
}
}*_
* }*