I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully-configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a .prefab
as expected. However, the Sprite
I'm assigning to my game object's SpriteRenderer
component is missing:
In my script, I'm assigning my SpriteRenderer
's sprite
property to a Sprite
object that I dynamically create in the script. Here's the relevant excerpt from my editor script:
GameObject gameObject = new GameObject(fileName);
SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
// texture size will be replaced during the LoadImage() call
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName + ".png")));
spriteRenderer.sprite = Sprite.Create(
texture,
new Rect(0.0f, 0.0f, texture.width, texture.height),
new Vector2(0.0f, 0.0f)
);
PrefabUtility.CreatePrefab("Assets/Prefabs/" + fileName + ".prefab", gameObject);
DestroyImmediate(gameObject);
I can verify through logging that the image path to my .png
is correct and that the Texture2D
and Sprite
objects seem to be instantiated correctly. For example, I can do this:
// logs "580" as expected
Debug.Log(texture.width);
What am I doing wrong? How can I save this game object as a .prefab
without losing its sprite information?
PrefabUtility.InstantiatePrefab
when later creating the prefab. \$\endgroup\$