Home > database >  Best Key to use when storing GameObjects in Hashtable? - Unity, C#
Best Key to use when storing GameObjects in Hashtable? - Unity, C#

Time:01-22

I'm working towards writing a script to take a "snapshot" of the initial attributes of all children of a GameObject. Namely at startup I want to save the position, orientation & color of all these objects in a Hashtable. The user has the ability to move & modify these objects during runtime, and I want to update the Hashtable to keep track of this. This will allow me to create an Undo last action button.

I found that gameObject.name isn't a good Key for my Hashtable entries because sometimes multiple game objects have the same name (like "cube"). So what would make a better Key? It's clear that Unity differentiate between two identical game objects with the same name, but how? I don't want to have to manually Tag every game object. I want to eventually bring in a large CAD file with hundreds of parts, and automatically record them all in a Hashtable.

For example, the code below works fine, unless I have multiple game objects with the same name. Then I get this error ArgumentException: Item has already been added. Key in dictionary: 'Cube' Key being added: 'Cube'

public class GetAllObjects : MonoBehaviour
{
    public Hashtable allObjectsHT = new();
    void Start()
    {
        Debug.Log("--Environment: GetAllObjects.cs <<<<<<<<<<");
        foreach (Transform child in transform)
        {
            allObjectsHT.Add(child.gameObject.name, child);
        }

    }
}

CodePudding user response:

Thanks Chuck this is what I want, and you solved my problem:

public class GetAllObjects : MonoBehaviour
{
    UnityEngine.Vector3 startPosition;
    UnityEngine.Quaternion startRotation;

    public Hashtable allObjectsHT = new();
    void Start()
    {
        Debug.Log("--Environment: GetAllObjects.cs <<<<<<<<<<");
        foreach (Transform child in transform)
        {
            startPosition = child.position;
            startRotation = child.rotation;
            Hashtable objHT = new();
            objHT.Add("position", startPosition);
            objHT.Add("rotation", startRotation);
            allObjectsHT.Add(child, objHT);
        }
    }
}

CodePudding user response:

It's good to use meaningful keys you can refer to, otherwise you'd just use a collection without keys like a List. You could use an editor script to name all of the objects you import and use the names as keys. e.g.

int i = 0;
foreach(GameObject g in Selection.gameObjects)
{
     g.name = "Object_"   i.ToString();
     i  ;
}

You could make the naming more sophisticated and meaningful of course, this is just an example.

  • Related