using UnityEngine;
using System.Collections;

public class DontDestroyStuff : MonoBehaviour {
	public GameObject[] objectsInScene, indestructibles = new GameObject[10];
	public bool done;
	public int x;
//	public int ammount;
	void Awake() 
	{
		DontDestroyOnLoad(transform.gameObject);
	}
	void Update()
	{
		if (!done) 
		{
			//take all the objects in the scene
			objectsInScene = (GameObject[])FindObjectsOfType(typeof(GameObject));
			//pick the ones that have the script to not be destroyed
			x = 0;
			for (int i = 0; i < objectsInScene.Length; i++) 
			{    
				if (objectsInScene[i].transform.parent == null)
				{
					if (objectsInScene[i].GetComponent<DontDestroyMe>() != null) {
						indestructibles[x] = objectsInScene[i];
						x++;
					}
				}

			}
			//if there's an object with the same name as another we destroy the one that has the value old == false
			for (int i = 0; i < x; i++) 
			{
//				Debug.Log("Check");
				if (indestructibles[i] != null) {
					for (int j = 0; j < x; j++) 
					{
						if (i != j ){
							if (indestructibles[i] != null) {

								if (indestructibles[j].name == indestructibles[i].name) {
//									Debug.Log("Match!");
									if (indestructibles[j].GetComponent<DontDestroyMe>().old) 
									{
										Destroy(indestructibles[i]);
									}else
									{
										Destroy(indestructibles[j]);
									}
								}
							}
						}
					} 

				}
			}
			for (int i = 0; i < indestructibles.Length; i++) 
			{
				if (indestructibles[i] != null) 
				{
//					Debug.Log("Hi");
					DontDestroyOnLoad(indestructibles[i]);
				}
			}
			for (int i = 0; i < indestructibles.Length; i++) 
			{
				if (indestructibles[i] != null) 
				{
					indestructibles[i].GetComponent<DontDestroyMe>().old = true;
				}
			}
		}
		done = true;
	}
	void OnLevelWasLoaded(int level) {
		done = false;
	}
}
