For lack of having a method to directly access individual sprites created by Unity, I found the following workaround to get the job done. This requires that the individual sprites in the texture are in a grid. Basically, instead of having Unity build the individual sprite frames, you build them yourself.
Add the sprite texture to your project as normal, with Type: “Sprite” and Sprite Mode “Single” (will not work if set to Multiple). I also have the Pixels to Units set to 1, which is consistent with the way I have my project setup. I then have the following class to build and allow access to the individual sprite frames:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MapDisplay : BaseBehavior
{
public Texture2D TilesTexture;
List<Sprite> _tileFrames;
private float TILE_UNIT_WIDTH = 48f;
private float TILE_UNIT_HEIGHT = 48f;
private int NUM_FRAMES_X = 8;
private int NUM_FRAMES_Y = 5;
// Use this for initialization
void Awake () {
SetupSpriteFrames();
}
// Update is called once per frame
void Update () {
}
public Sprite GetSpriteFrame(int tx, int ty)
{
return (tx >= 0 tx < NUM_FRAMES_X ty >= 0 ty < NUM_FRAMES_Y) ? _tileFrames[ty * NUM_FRAMES_X + tx] : _tileFrames[0];
}
private void SetupSpriteFrames()
{
_tileFrames = new List<Sprite>();
Vector2 pv = new Vector2(0f, 0f);
for (int j = 0; j < NUM_FRAMES_Y; j++)
{
for (int i = 0; i < NUM_FRAMES_X; i++)
{
Rect loc = new Rect(i * TILE_UNIT_WIDTH, (NUM_FRAMES_Y - (j+1)) * TILE_UNIT_HEIGHT, TILE_UNIT_WIDTH, TILE_UNIT_HEIGHT);
Sprite s = Sprite.Create(TilesTexture, loc, pv, 1f);
_tileFrames.Add(s);
}
}
}
}
Note: BaseBehavior, in addition to being mis-spelled, is just a wrapper around MonoBehaviour, and my tile size in pixels is 48x48.
Once you attach this script to a GameObject, drag the texture you imported into the TilesTexture property and you should be good to go.
Here is an example of how the class is then used, where the individual frame is identified by its x and y coordinates within the texture image starting at the top left:
public void SetTileGraphic(MapTerrain mt, MapDisplay parentMap)
{
// get reference to sprite renderer
SpriteRenderer sr = this.transform.FindChild("MapTileSprite").gameObject.GetComponent<SpriteRenderer>();
switch (mt.TerrainType)
{
case MapTerrain.TERRAIN_FOREST:
sr.sprite = parentMap.GetSpriteFrame(1, 0);
break;
case MapTerrain.TERRAIN_HILLS:
sr.sprite = parentMap.GetSpriteFrame(2, 0);
break;
case MapTerrain.TERRAIN_WATER:
sr.sprite = parentMap.GetSpriteFrame(3, 0);
break;
case MapTerrain.TERRAIN_PLAINS::
sr.sprite = parentMap.GetSpriteFrame(0, 0);
break;
}
}
Still hoping there is a way to reference Sprites created in the editor via code, either which I do not know about, or in a future release.