Skip to content

KeepOnPage.cs

MuNgLo edited this page Aug 1, 2014 · 2 revisions

A small C# script that helps you keep a UI gameobject on the active page. Like an achievement popup and stuff like that.

Save the code bellow as a separate script and make sure it is loaded after OpenGUI in the compilationorder. It will on startup register all child gameobjects as separate items in a list and under FixedUpdate() it will make sure all in the list have the currentpage as parent.

Note that it keeps track of objects by name so all objects must have unique name. Also note that if you want to delete the objects you need to add the appropriate code. Lastly it is intended for just a few objects. No thought has gone into optimizing or performance. So if you choose to handle thousands of objects this way, well good luck. 😉

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class keepOnPage : MonoBehaviour
{
    // Make sure all tracked objects have a unique name
        private OGRoot UIRoot;
        public List<GameObject> keepList = new List<GameObject> ();
        void Start ()
        {
                UIRoot = GameObject.Find ("GUIRoot").GetComponent<OGRoot> ();
        }

        void FixedUpdate ()
        {
                foreach (Transform child in transform) {

            if( !keepList.Exists ( item => item.name == child.name ) ){
                                keepList.Add (child.transform.gameObject);
                        }
                }

                setParents (UIRoot.currentPage.transform);
        }

        void setParents (Transform parent)
        {

                foreach (GameObject keep in keepList) {
                        keep.transform.parent = parent;
                }

        }
}

Clone this wiki locally