Skip to content

Instantly share code, notes, and snippets.

@prhiggins
Created March 30, 2017 04:48
Show Gist options
  • Select an option

  • Save prhiggins/17682264d109f1a09bd1c34376d5aab9 to your computer and use it in GitHub Desktop.

Select an option

Save prhiggins/17682264d109f1a09bd1c34376d5aab9 to your computer and use it in GitHub Desktop.
spot the lambda
using UnityEngine;
using System.Collections;
public class WorldController : MonoBehaviour {
public Sprite floorSprite;
// The world and tile data
World world;
// Use this for initialization
void Start () {
// Create a world with Empty tiles
world = new World();
// Create a GameObject for each of our tiles, so they have a visual component
for (int x = 0; x < world.Width; x++) {
for (int y = 0; y < world.Height; y++) {
// Get the tile data
Tile tile_data = world.GetTileAt(x, y);
// Create new GameObject, add to scene
GameObject tile_go = new GameObject();
tile_go.name = "Tile_" + x + "_" + y;
tile_go.transform.position = new Vector3( tile_data.X, tile_data.Y, 0);
// Add a sprite renderer to tile - do not set sprite yet, that is done is worldgen
tile_go.AddComponent<SpriteRenderer>();
// Use a lambda to "wrap" our callback function
tile_data.RegisterTileTypeChangedCallback( (tile) => { OnTileTypeChanged(tile, tile_go); } );
}
}
// Shake things up, for testing.
world.RandomizeTiles();
}
// Update is called once per frame
void Update () {
}
// This function should be called automatically whenever a tile's type gets changed.
void OnTileTypeChanged(Tile tile_data, GameObject tile_go) {
if(tile_data.Type == Tile.TileType.Floor) {
tile_go.GetComponent<SpriteRenderer>().sprite = floorSprite;
}
else if( tile_data.Type == Tile.TileType.Empty ) {
tile_go.GetComponent<SpriteRenderer>().sprite = null;
}
else {
Debug.LogError("OnTileTypeChanged - Unrecognized tile type.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment