I’ve started work on a very simple tile importer and have hit a bit of a snag.
I can easily create the sprites and the game objects, add sprite rendere to the game object and connect the sprite to the sprite rendere. But when I create a prefab from the game object, the reference to the sprite is lost?
Do I need to store the created sprites in some way? Or are there some parameters I must provide when creating the sprites?
Here’s what I got so far.
public class PrefabTest : MonoBehaviour
{
public Texture2D TilesTexture;
private float TILEWIDTH = 64f;
private float TILEHEIGHT = 64f;
private int FRAMES_X = 16;
private int FRAMES_Y = 16;
private List<Sprite> spriteList;
void Awake()
{
spriteList = new List<Sprite>();
Vector2 pv = new Vector2(0f, 0f);
for (int y = 0; y < FRAMES_Y; y++)
{
for (int x = 0; x < FRAMES_X; x++)
{
Rect loc = new Rect(x * TILEWIDTH, (FRAMES_Y - (y + 1)) * TILEHEIGHT, TILEWIDTH, TILEHEIGHT);
Sprite s = Sprite.Create(TilesTexture, loc, pv, 64f);
s.name = "sprite" + (x + y * FRAMES_Y).ToString("d4");
spriteList.Add(s);
}
}
}
// Use this for initialization
void Start()
{
for (int y = 0; y < FRAMES_Y; y++)
{
for (int x = 0; x < FRAMES_X; x++)
{
GameObject newTile = new GameObject();
SpriteRenderer spriteRenderer = (SpriteRenderer)newTile.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = spriteList[x + y * FRAMES_Y];
newTile.transform.position = new Vector3(x, -y, 0f);
newTile.name = "Tile" + (x + y * FRAMES_Y).ToString("d4");
PrefabUtility.CreatePrefab("Assets/Temporary/" + newTile.gameObject.name + ".prefab", newTile, ReplacePrefabOptions.ConnectToPrefab);
}
}
}
}
All the created game objects (not the prefabs) are shown perfectly…
Any help would be appreciated.
- Henning