Exemple #1
0
    // Use this for initialization
    void Awake()
    {
        _navController = new NavController();

        GameObject mapGridGameObject = GameObject.FindWithTag("MapGrid");

        if (mapGridGameObject == null)
        {
            Debug.LogError("Could not find mapGrid by tag to initialize MapController.");
        }

        _mapGrid = mapGridGameObject.GetComponentInChildren <Grid>();
        if (_mapGrid == null)
        {
            Debug.LogError("Could not find Grid on GameObject with 'Map' tag.");
        }

        // Init map model from terrain tilemap
        terrainTilemap = GameObject.FindGameObjectWithTag("TerrainTilemap").GetComponent <Tilemap>();
        if (terrainTilemap == null)
        {
            Debug.LogError("Could not find Tilemap on GameObject with 'Map' tag.");
        }

        _mapModel = new MapModel(terrainTilemap);

        // Spawn trees based on tree tilemap
        GameObject treeContainer = new GameObject("Trees");

        treeContainer.tag = "Trees";
        GameObject treeTileMapGameObject = GameObject.FindGameObjectWithTag("TreeTilemap");
        Tilemap    treeTilemap           = treeTileMapGameObject.GetComponent <Tilemap>();

        if (treeTilemap == null)
        {
            Debug.LogError("Could not find Tilemap on GameObject with 'Map' tag.");
        }
        BoundsInt tileMapBounds = treeTilemap.cellBounds;

        for (int x = tileMapBounds.xMin; x <= tileMapBounds.xMax; x++)
        {
            for (int y = tileMapBounds.yMin; y <= tileMapBounds.yMax; y++)
            {
                TileBase treeTile = treeTilemap.GetTile(new Vector3Int(x, y, 0));
                if (treeTile)
                {
                    Vector2Int treeCell          = new Vector2Int(x, y);
                    Vector3    treeWorldPosition = GetCellCenterWorld(treeCell);
                    GameObject treeGameObject    = GameObject.Instantiate(treePrefab, treeWorldPosition, Quaternion.identity, treeContainer.transform);
                    treeGameObject.GetComponent <SpriteRenderer>().sortingOrder = Mathf.FloorToInt(-4 * treeWorldPosition.y);
                    _mapModel.AddTree(treeGameObject, treeCell);
                }
            }
        }

        GameObject.Destroy(treeTileMapGameObject);

        // Initialize navController after Trees are placed
        navController.mapModel = _mapModel;
    }