iTweenの終了

unity3D のトゥイーンライブラリ「iTween」を使っていて、少しずつメモリが溜まっていく問題に悩まされたのでメモ。

トゥイーンが終了する前にDestroyすると開放されない。好きなタイミングでDestroyする場合は、あらかじめ OnDestroy で iTween.Stop() するスクリプトを貼り付けとく。LoadLevelでシーンを切り替える場合は、すべてのオブジェクトがDestroyされるので、これをやっといたほうがいいと思う。



サンプル




MainScript.cs
using UnityEngine;
using System.Collections;

public class MainScript : MonoBehaviour {
 public GameObject prefab;
 public int num = 100;
 
 void Start () { }

 void Update () {
  for( int i=0; i<num; i++){  
   
   GameObject go = (GameObject)Instantiate( prefab );
   
   Hashtable hash = new Hashtable();
   hash.Add( "time", 1.0f );
   hash.Add( "position", new Vector3( Random.Range(-100,100), 0,  Random.Range(-100,100) ));
   iTween.MoveTo( go, hash );
   
   go.AddComponent<ChildScript>();
   Destroy( go, 0.5f );
   
  }
 }
}


ChildScript.cs
using UnityEngine;
using System.Collections;

public class ChildScript : MonoBehaviour {

 void Start () { }
 
 void Update () { }
 
 void OnDestroy(){
  iTween.Stop();
 }
}




なお、GoKit という別のトゥイーンライブラリでは、Destroy するだけで終了してくれた。