- Home /
Creating Prefabs via Code the renderer loses Sprite.
Hello, i need to create prefabs for many items, so i chose to use a script to do that:
[MenuItem("Assets/Generate WorldArt Sprite Prefab")]
static void Execute() {
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
string destPath = string.Format("Assets/Prefabs/worldart/{0}.prefab",Path.GetFileNameWithoutExtension(path));
Texture2D tex = (Texture2D)Selection.activeObject;
Sprite s = Sprite.Create(tex, new Rect(0,0,64,64), new Vector2(0,0));
GameObject go = new GameObject();
SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
sr.sprite = s;
PrefabUtility.CreatePrefab(destPath, go);
}
The problem is that, after running the script, i find the Prefab to be without the sprite but with the spriterenderer, as you can see below.
I followed the script with VS debugger, and i'm not casting anything to null.
Does anyone know what's happening? Thanks a lot!
Nope, i do not... I switched to loading textures from Resources folder, but i still have problems because unity cannot handle as many Resources as i want to.... :\ That's pretty messed up!
Answer by Paulius-Liekis · Jan 15, 2015 at 02:30 PM
Your sprite doesn't exist in Project space - it was create and lives in Scene space, so you prefab (which lives in Project space) can not reference object which does not exist in Project space.
Add your sprite to your prefab using AssetDatabase.AddObjectToAsset.
Your answer
![](https://koobas.hobune.stream/wayback/20220613175051im_/https://answers.unity.com/themes/thub/images/avi.jpg)