- Home /
Find GameObject with value within script
Hoping to get some help here, I may be doing things a little backward and still new to Unity
I have GameObjects that are instantiated with pre-assigned unique ID values in an attached script and then have a menu open for each GameObject when requested (double click said object). I can get the values from the GameObject just fine to display but i'm having a hard time understanding how to assign values back to the unique ID GameObject.
I was reading maybe doing a search for all GameObjects into an array and then searching for said unique ID inside their attached script?
I'm working in 2D if that helps at all
I found a different solution to this, but am still interested if anyone has the answer.
Because when i instantiate the GameObject i created a way to make each name unique and then later i can do a GameObject.Find(UniqueID) and then modify the values that way.
Can't you just use Object.GetInstanceID ? Why do you want to modify an ID?
Answer by IggyZuk · Apr 08, 2017 at 02:35 PM
You can use a Dictionary of GameObjects with id as the key.
Dictionary<int, GameObject> objects = new Dictionary<int, GameObject>();
int nextObjectId = 0;
public void AddObject()
{
objects.Add(nextObjectId, new GameObject(nextObjectId.ToString()));
nextObjectId++;
}
public GameObject GetObjectWithId(int id) {
if (objects.ContainsKey(id)) {
return objects[id];
}
Debug.LogWarningFormat("Object with id: {0} doesn't exist!", id);
return null;
}
Answer by Zymu · Apr 08, 2017 at 11:03 PM
If you want it to be a little more efficient than a GameObject.Find() you can store all instantiated items in a list or an array and create a search function to find the one you want.
using System.Collections.Generic;
...
List<GameObject> objectList = new List<GameObject>();
void InstantiateObject() {
GameObject go = Instantiate(myObject) as GameObject;
objectList.Add(go);
}
GameObject FindObjectByID(string ID) {
GameObject result = null;
for (int i = 0; i < objectList.Count; i++) {
if (objectList[i].GetComponent<(your class)>().id == ID) {
result = objectList[i];
break;
}
}
return result;
}
If you're not working with a ton of objects, a tag or name GameObject search will be fine. This just reduces the amount of items you have to sift through to find the one you're trying to find. If you're working with very few items, you can store instantiated objects to global variables the same way.
Your answer
Follow this Question
Related Questions
Unload from memory - GameObject in an array? 1 Answer
How to set to game objects's position from 2 different game objects arrays equal to each other? 0 Answers
What is the best way to instatiate an array of connected GameObjects? 0 Answers
Transport unknown amout of objects with GameObject array 0 Answers
View an array of the transform position/rotation of all game objects with a specified tag., 0 Answers