- Home /
How to Instantiate objects while in editor?
I use a lot of auto-generated code when I'm working on a project (procedural terrain, loading objects from json, etc), whitch is great but how its set up I have to run before I can see anything in my scene. This is very annoying so I was wondering if there is a better way to do things. What I end up doing with most of my code is something like this.
public List<GameObject> myObjects;
public List<GameObjects> CreateObjects(int numberOfObjects) {
var list;
for(int i = 0; i < numberOfObjects; i++) {
var newObj = Instantiate(prefab, pos, rot) as GameObject;
newObj.transform.parent = transform;
newObj.getComponent<dataStruct>().data = jsonData;
list.Add(newObj);
}
return list;
}
void Start() {
myObjects = CreateObjects(10);
}
Is there a better way of doing this that will run in the editor? Maybe if I made this function static? But then how would I access transform or other parts that depend on the GameObject?
Answer by Dave-Carlile · Feb 22, 2016 at 01:01 PM
The ExecuteInEditMode attribute is a starting point for you. It allows your scripts to run in edit mode which will let you create objects like that in the editor. You can think of Unity as "the game" and so all of the same things you would in a game. But you likely will have to pay attention to Unity's scene serialization and some other interesting object lifetime sort of things.
I don't have much experience in creating rock sold in-editor code, but using that attribute or "custom editor" as a starting point for your research should get you moving in the right direction.
Awesome! This works very well with some of my scripts already. I'll have to look into custom editor more.
Your answer
![](https://koobas.hobune.stream/wayback/20220612065135im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Spawning objects on trigger does not work as expected 2 Answers
Static Batching with Asset Bundles 1 Answer
Instantiation working in editor, not in build. 0 Answers
instantiate in the editor (Prefab Problem) 1 Answer
Trying to run 5 instances of a static method at once to do an action, probably a dumb thing to do? 0 Answers