- Home /
Creating sprite in code using TextureImporter with C#?
I'm trying to create a Sprite based on an external texture. The intended functionality once I finish is that a user would be able to select a photo from an external source and use that as their sprite. My problem is trying to convert that texture into a sprite, which so far I haven't been able to do.
using UnityEngine;
using UnityEditor;
public Material defaultMaterial; //prefab material set already
IEnumerator Start()
{
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
string path = "file://C:\\Users\\i5\\Documents\\My2DProject\\Assets\\oranges.png";
TextureImporter tImport = AssetImporter.GetAtPath(path) as TextureImporter;
TextureImporterSettings tImportSettings = new TextureImporterSettings();
tImport.isReadable = true;
//Throws an error NullReferenceException: Object reference not set to an instance of an object
tImport.textureType = TextureImporterType.Sprite;
tImportSettings.spriteMode = 1;
tImport.SetTextureSettings(tImportSettings);
renderer.sprite = //How can I convert the oranges.png texture into a sprite with TextureImporter tImport? I'm stuck on this part.
renderer.material = defaultMaterial;
}
Answer by Stone-Legion · Nov 23, 2013 at 01:19 AM
Solved my problem, here is the solution. Note you can swap the path for a URL if you want to load an image from the web.
using UnityEngine;
using UnityEditor;
public Material defaultMaterial; //prefab material set already
IEnumerator Start()
{
string path = "file://C:\\Users\\i5\\Documents\\My2DProject\\Assets\\oranges.png";
WWW www = new WWW(path);
yield return www;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = new Sprite();
sprite = Sprite.Create(www.texture, new Rect(0, 0, 170, 170),new Vector2(0, 0),100.0f);
renderer.sprite = sprite;
renderer.material = mat;
}
For more see http://docs.unity3d.com/Documentation/ScriptReference/Sprite.Create.html
Hey, I'm searching for the same functionality. What do you mean by "prefab material set already" ? How do I do that? Thanks.
nice information.. but now the picture's quality will be down (resolution). how to make the picture's resolution same with the picture real ??
Your answer

Follow this Question
Related Questions
Sprite Renderer is wrapping bottom pixel when it shouldn't be 1 Answer
Override texture import path 0 Answers
How to skip already imported textures on AssetPostprocessor change? 3 Answers
Custom Pivot Points in Sprite Editor 1 Answer
Differentiating between first import and reimport in the TextureImporter 0 Answers