- Home /
Sprite.Create is not working
void OnPostprocessTexture(Texture2D texture)
{
GameObject go = new GameObject("TEST");
SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
sr.sprite = Sprite.Create(texture, new Rect(0,0,500,500), new Vector2 (0.5f, 0.0f));
}
The above sample code does not work properly. The sprite does not point to any Sprite texture. The SpriteRenderer's sprite points to none in the Inspector. However it seems like the data was valid while walking through the code. What is the problem here?
I use Sprite.Create succcessfully, so it's probably some weird issue. (0,0,500,500) means a box from 0,0 to 500,500; 0.5f,0.0f means the pivot will be top-center. Would these settings put the object out of view?
Is it possible to create gameobjects during the import process? That seems like an easy way to create memory leaks, perhaps Unity blocks it. Have you tried using a [$$anonymous$$enuItem("")] function?
I made it big so that I can see it easily. It creates a sprite which I would like to assign to a SpriteRenderer but it just points to nothing. Also the pivot point should point to the Bottom.
Yes it is possible to create gameobjects during the import process, but make sure you call DestroyImmediately to delete it once you are done. I am using it to create prefabs. I am trying to automate the import process to create prefabs so a $$anonymous$$enuItem won't do for me :(
I tried several code variations but it still doesn't work no matter what I do. It is like Sprite.Create is doing something funky with the texture. Even tried both OnPostprocessTexture and OnPostprocessAllAssets, same thing. Of course, it works great during runtime code, but that is not what we want.
If anyone is able to do Sprite.Create fine in these 2 functions, please post them as answers!
Of course it's bottom-center, why would we have any consistency in our coordinate systems. Consistency is for lazy people. [/sarcasm]
$$anonymous$$y only other suggestion is, is the texture a Sprite-type texture? You might need to do things with TextureImporter to be sure you have a Sprite texture to work with.
What texture is actually being passed to the function? I do not know if you have it set in the inspector, or if you set it elsewhere? Are you trying to do this for a texture in a folder, automatically? Is the texture actually 500x500? Just looking for info.
Answer by Janibasha · Dec 27, 2017 at 11:41 PM
Rect rect = new Rect(0, 0, 8, 8); ==>> use 8x8 or as in ur error like 64x64 then Rect rect = new Rect(0, 0, 64, 64); ArgumentException: Could not create sprite (0.000000, 0.000000, 64.000000, 64.000000) from a 8x8 texture.
fbpic.sprite = Sprite.Create(result.Texture, rect, new Vector2(0f, 0f), 125);