Search Unity

Automatically create sprite game objects from textures in project folder

Discussion in 'Scripting' started by startas, Jun 17, 2018.

  1. startas

    startas

    Joined:
    Nov 14, 2014
    Posts:
    102
    What would be the fastest way to automatically create sprite game objects from textures in project folder ? I wanna do this all with code, because it would take insane amount of time to do it all in editor, and if will make some mistake, then i would have to redo everything again.

    I have all textures (png and jpg files) in project folder "Assets/Resources/abc/". Would this be correct way of doing this ? :
    1. Use Resources.Load("abc/texture_1") to load textures into Texture2D objects;
    2. Create sprites from Texture2D objects using Sprite.Create(/*set all settings to what i need*/);
    3. Create new game object, add SpriteRenderer component to it;
    4. Assign before created sprite to sprite variable of just created game object;
    5. Loop it through all textures.

    Is there a better way to do this ?
     
  2. Sghwarzengold

    Sghwarzengold

    Joined:
    Jul 6, 2015
    Posts:
    13
    We use this way in our games and it works fine
     
  3. I may be wrong, because I haven't tried it yet (I didn't need to do this kind of thing ever), but I would try to build this in the editor using this: https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessAllAssets.html
    If this work (iterate over the imported textures and create the proper game objects you need for each of them), you need to this once in the editor, which would mean you don't need to do it run-time.
    But as I said, I'm not sure if it's a viable solution.