Hey,
I want to load the new 2D Sprites by asset bundle. The problem is that Unity handles and exports Sprites as Texture2D objects.
My question is, how do I get a Sprite out of this loaded Texture2D object?
Hey,
I want to load the new 2D Sprites by asset bundle. The problem is that Unity handles and exports Sprites as Texture2D objects.
My question is, how do I get a Sprite out of this loaded Texture2D object?
I’ve been poking around with this recently and was able to get the sprite back from the asset bundle, but it does appear like it was not well thought through.
I create the asset bundle using the following
UnityEngine.Object[] assets = new UnityEngine.Object[] { AssetDatabase.LoadAssetAtPath( MySpritePath, typeof(UnityEngine.Object) ) };
UnityEngine.Object mainAsset = assets[0];
BuildPipeline.BuildAssetBundle( mainAsset, assets, bundlePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, buildTarget );
Then load it up with
AssetBundle bundle = AssetBundle.CreateFromFile("bundlePath");
spriteRenderer.sprite = bundle.Load( "MySpriteName", typeof(Sprite) ) as Sprite;
and I get a sprite back with all the right settings. Looking into it further I found that even though during the bundle building step it appears as if only one asset is added (the assets array has length 1), when you load the bundle it actually contains two assets: the Texture2D and the Sprite. This also appears to hold true when you have multiple sprites per texture, it looks like you’re only adding one asset, but somewhere along the way they all end up in the bundle.
If you a experimenting and want to see what is actually in the bundle you can do a LoadAll and enumerate the contents
Object[] assets = bundle.LoadAll();
foreach ( Object asset in assets ) {
Debug.Log( "loaded asset " + asset.name + " of type " + asset.GetType() );
}
As mentioned above, Sprite.Create(…) should be able to get the job done depending on what your use-case is. The following code snippet worked for me. Hope this helps.
if (_iconsBundle.Contains(iconName))
{
var iconTexture = _iconsBundle.Load(iconName) as Texture2D;
var iconRect = new Rect(0, 0, iconTexture.width, iconTexture.height);
var iconSprite = Sprite.Create(iconTexture, iconRect, new Vector2(.5f, .5f));
worldIcon.sprite = iconSprite;
}
else
{
worldIcon.sprite = defaultIcon;
}
The textures are treated as sprites. E.g. If you have in your code something like
public Sprite mySprite;
You’ll be able to drag the sprite texture to fill that spot.
As far as I can tell, as of 4.3.4, you cannot.
When Texture2D assets and their sprites are saved to an AssetBundle, the Sprite information is dropped.
If you only have a single sprite within a texture, you could recreate the sprite at runtime with Sprite.Create, but obviously this isn’t ideal.
You can use Resources.LoadAssetAtPath to load Sprite object instead of AssetDatabase.LoadAssetAtPath:
Resources.LoadAssetAtPath(path, typeof(Sprite));