Friday, August 12, 2011

Small Utility Class for Unity3D

To avoid the costly gameobject.find() method I wanted a way to register objects into a "database" that could be queried at o(1) complexity. To do that, you need to generate unique IDs for objects, a GUID if you will. A hashtable is a great collection to do this with - so I wanted to write a simple wrapper for a hashtable ( I will call it hashlist) that would make code easier to read.

I use this class to hold 'databases' of run-time objects in several classes. Remotely connected players, Network synchronized items and states, as well as a list of objects that are currently being 'inspected' by the player.

This is a generic implementation to accept Transforms which will need to be casted to the correct object type on retrieval.

This class will be used by other examples in newer posts.


using System;
using System.Collections;
using UnityEngine;


    //Class to store list of transforms to facilitate easy retrieval
    public class Hashlist
    {
        //List of NPCs in the World
        private Hashtable List = new Hashtable();


        public Hashtable GetList()
        {
            return List;
        }


        public void OverriteList(Hashtable newlist)
        {
            List = newlist;
        }


        public string AddItemToList(string guid, Transform obj)
        {
            if (guid == "")
                guid = obj.name + obj.position.x;
            List.Add(guid, obj);


            //Debug.Log("added item to list with guid: " + guid);
            return guid;
        }
        public void RemoveItemFromList(string guid)
        {
            List.Remove(guid);
        }
        public Transform GetItemFromList(string guid)
        {
            return (Transform)List[guid];
        }
        public bool DoesItemExist(string guid)
        {
            return List.ContainsKey(guid);
        }
        public int Clear()
        {
            int deleted = 0;
            List.Clear();


            return deleted;
        }
        public bool IsEmpty()
        {
            return (List.Count == 0);
        }
    }

No comments:

Post a Comment