Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Iterating over prefabs for code generation

Discussion in 'Prefabs' started by supernameworld, May 9, 2021.

  1. supernameworld

    supernameworld

    Joined:
    Sep 14, 2015
    Posts:
    16
    I am trying to do some code generation which creates an entry in an enum for each prefab in a given subfolder, and attaches a reference to each prefab inside of a resource manager class.

    I've done code generation before, and setting up the resource manager is easy, but I don't understand how to:
    1. iterate over prefabs
    2. get the filenames of the prefabs
    3. get references to the prefabs which I can assign to fields in a MonoBehavior or ScriptableObject

    What is the correct way of doing this?
     
  2. pietrodenicola

    pietrodenicola

    Unity Technologies

    Joined:
    Dec 8, 2020
    Posts:
    43
    See first if you can get a list of your prefabs paths with some code like this:
    Code (CSharp):
    1. DirectoryInfo dir = new DirectoryInfo(yourPrefabsFolder);
    2. FileInfo[] info = dir.GetFiles("*.prefab");
    3. foreach (FileInfo file in info)
    4. {
    5.     Debug.Log(file.ToString());
    6. }
    Then getting references should be easy like this:
    Code (CSharp):
    1. var yourPrefab = AssetDatabase.LoadMainAssetAtPath(path) as GameObject;
     
    Last edited: May 17, 2021