You could use something like that. Maybe some elements from other classes are missing, modify it for your need.
On mobile you really want to reuse elements. Every time garbage collector does his job, you get a slight delay. Here you only create instance if you are lacking them.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
///
/// This is an object factory. Instances of game objects are being reused so there is no garbage produced.
///
public class ObjectFactory : MonoBehaviour {
///
/// Reference to object that holds all the variations.
///
public Transform variationsObject;
///
/// Holds POSSIBLE! variations of game object.
///
private List variations = new List();
///
/// Holds available instances of gameObject.
///
protected List holder = new List();
protected List activeObjects = new List();
protected void Start () {
Debug.Log ("Started! " + variationsObject.childCount);
for(int i = 0; i < variationsObject.childCount; i++) {
variations.Add ((GameObject)GameObject.Instantiate(variationsObject.GetChild(i).gameObject));
}
}
///
/// returns instance of game object.
///
/// The object of index.
/// Index.
private GameObject GetInstanceByIndex(int index) {
var go = GetInstance ();
go.GetComponent().sprite = variations[index].GetComponent().sprite;
return go;
}
protected GameObject GetInstance() {
var result = holder.Count > 0 ? holder.Pull() : (GameObject)GameObject.Instantiate(variations[Random.Range(0, variations.Count)]);
result.SetActive(true);
result.renderer.enabled = true;
return result;
}
///
/// Creates and positions element on given position
///
/// Position.
public virtual GameObject PositionOn(Vector2 position) {
var obj = GetInstance();
obj.transform.position = position;
activeObjects.Push(obj);
return obj;
}
///
/// Updates all active elements
///
public virtual void UpdateElements() {
for(int i = 0; i < this.activeObjects.Count; i++) {
var obj = activeObjects[i];
obj.transform.Translate(Vector2.up * -1 * Config.Instance.gameSpeed * Time.deltaTime);
if(!obj.renderer.enabled || obj.transform.position.y + obj.renderer.bounds.size.y < Config.Instance.bottomY)
ReleaseInstance(activeObjects[i]);
}
}
///
/// Returns instance of GameObject back for reuse.
///
/// Game object.
public void ReleaseInstance(GameObject gameObject) {
gameObject.SetActive(false);
activeObjects.Remove(gameObject);
holder.Push(gameObject);
}
}
↧