Preventing name duplication in Hierarchy(getting selected GameObject)
I'm trying to write a script that would prevent user from having two gameObjects with the same name. For that I subscribed to the EditorApplication.hierarchyWindowChanged
event.
I wrote some code that loops trough all gameObjects in the scene and finds duplicates. It works great, my problem is just that it always gets the first item that is duplicated. But I am trying to get the item that was renamed to match witch another(that was selected at that time).
int count1 = 0, count2 = 0;
foreach (GameObject obj in UnityEngine.Object.FindObjectsOfType(typeof(GameObject)))
{
foreach (GameObject obj2 in UnityEngine.Object.FindObjectsOfType(typeof(GameObject)))
{
if (count1 != count2 && obj.name == obj2.name)
{
obj.name += "0";
}
count2++;
}
count1++;
count2 = 0;
}
To prevent duplication I am adding "0" to a duplicated object, but of course, not always to the selected one but always to the first in list.
Sorry, but I am just curious as to why you would want this? Are you instantiating objects where the name matters? Not being a jerk i am just curious because this forum is where I pretty much learned coding -or fixed coding- and it sounds like it could be useful if I knew what it was for.
I use a plugin called NodeCanvas for creating dialogue trees with IDs to link with a localization dictionary. IDs must be unique and are created via several parameters: gameObject name, node ID, actor name etc.. So in order to avoid duplicates I need all gameObject names to be unique. Just to make it clear: $$anonymous$$y code is working, just not how I want it to. I am trying to get the selected gameObject and not the first in the list that has a duplicate.
Answer by tormentoarmagedoom · Apr 26, 2018 at 08:01 AM
Good day. I dont understand exactly what you need.
When you find a coincidence, you can store that object in a new GameObject variable decloared at the begining of the script.
You can also check the name of the object, if contains some word. Si, when find a conicidence, add some word instead of a "0", like
obj.name += "Duplicated";
Then you can use
if (obj.name.Contains("Duplicated")
{
....
}
I'm not sure if i helped you haha :D
Bye!
You pretty much created a slight paradox here!
In order for the code to recognize the duplicate, you want to add "Duplicated" to the name, which already removes the duplication, since it no longer has the same name.
I see where you're going but my issue lies right here: obj.name += "something.." doesn't always rename name of selected objects.