Problem renaming prefab instance in scene (from custom editor window)
I'm creating a custom editor window where I want to list all Objects in the current scene that has a WayPoint script attached to them. I need all Objects in this list to have unique names because I later want to use GameObject.Find(object.name) to make a reference to each GameObject.
Here is my code:
void Example() {
// Find all objects with Waypoint script
Object[] objectArray = Resources.FindObjectsOfTypeAll(typeof(WayPoint));
// A list with all duplicate names
List<Object> duplicateNames = objectArray.GroupBy(s => s.name)
.SelectMany(grp => grp.Skip(1).ToList()).ToList();
// Renaming
for(int i = 0; i < duplicateNames.Count; i++) {
duplicateNames[i].name = duplicateNames[i].name + (i + 1);
}
}
This works fine for regular gameobjects, but with prefabs i seems like I'm changing the name of the prefab asset rather than the name of the prefab instance in the scene. So for each iteration of the for loop I am renaming all instances of that prefab.
Is there a way to rename the instance of the prefab rather than the prefab itself?
Answer by Serellyn · May 28, 2018 at 12:16 PM
I do realize this is a very old topic, and you probably have your solution already, but for people that are experiencing the same issue... When you want to change the name of your instance rather than your prefab, make sure you have declared your instance as a variable. Let me show you the incorrect and correct answer.
Changes the name of the prefab:
GameObject sq = prefab;
Instantiate(sq, new Vector3(0, 0, 0), Quaternion.identity);
sq.name = "new name";
Changes the name of the instanced object:
GameObject sq = prefab;
var i = Instantiate(sq, new Vector3(0, 0, 0), Quaternion.identity);
i.name = "new name";
Your answer
Follow this Question
Related Questions
Instantiate prefab on inspector drop 0 Answers
Unity overwrites prefab values in runtime 0 Answers
OnTriggerEvent Instatiate one prefab 0 Answers
No Script option in component Menu?! (Unity 5.3.1) 3 Answers
prefabs break movement scripts, 0 Answers