- Home /
How to iterate all prefabs in project and create them in scene
Hi there, I'm very new to Unity Programming so I'm not sure what's possible and what is not. I didn't see this question asked before so here goes.
What I am looking to do is iterate through all the prefabs in a particular directory in my project and create/destroy them in scene so some operations can be performed.
essentially
var directory = "\assets\objects\items\";
foreach(var prefab in directory) {
Create(prefab)
// do something with prefab
Destroy(prefab)
}
Is this possible? Or can you only iterate objects already in a scene?
If so, how would you do it, and how do you create/destroy those prefabs?
So this is ended up being the solution I went with:
IEnumerable>string< assetFolderPaths = AssetDatabase.GetAllAssetPaths().Where(path => path.EndsWith(".prefab") && path.Contains(pathFilter));
IEnumerable>string< assets = assetFolderPaths.Select(item => AssetDatabase.LoadAssetAtPath(item, typeof(GameObject))).Cast>GameObject<().Where(obj => obj != null);
int i = 0;
foreach (GameObject obj in assets) {
obj.rigidbody.useGravity = false;
var newObject = Instantiate(obj, new Vector3(i++ * 100.0f, 0, 0), Quaternion.identity) as GameObject;
_items.Add(newObject);
}
Answer by dannyskim · Jul 03, 2012 at 07:09 PM
Take a look at this following link:
http://answers.unity3d.com/questions/234935/how-do-i-enumerate-the-contents-of-an-asset-folder.html
This shows you how to iterate through the returned objects in a directory. After you get the returned data paths, you could simply:
Instantiate( Resources.Load( "assetDataPathHere" ) );
And destroy the cached object when you need to accordingly.
How would I load the prefab without Unity telling me that a String isn't an object?
Answer by Luci85 · Jul 03, 2012 at 07:20 PM
An easy solution is assigning all prefabs with a tag and just gather all gameobjects with the same tag:
var gameobjects:GameObject[] = GameObject.FindGameObjectsWithTag("PrefabTag");
And then loop through all gameobjects:
for(var gameobject:GameObject in gameobjects)
{
Create(gameobject)
// do something with prefab
Destroy(gameobject)
}
This will only work for prefabs already instantiated in the scene unfortunately.
Your answer
Follow this Question
Related Questions
Making a cloned particle emitter fire once only 2 Answers
How to create object using onCollisionEnter trigger function ? 1 Answer
Unity 2021 (Blank Preview Icons and shaders in Project browers are pink but work.) 0 Answers
DestroyImmediate Prefabs 3 Answers
Unable to create project. Ver 3.0.0 1 Answer