protected bool unitMoving = false; // set when a unit is moving and no input should be accepted #endregion // ------------------------------------------------------------------------------------------------------------ #region start protected void Start() { // get reference to the mapnav map map = GameObject.Find("Map").GetComponent <Sample4Map>(); // also used in sample4b if (map == null) { map = GameObject.Find("Map").GetComponent <Sample4bMap>(); } // in this sample I will simply spawn 10 units on random locations of the map for (int i = 0; i < 10; i++) { Sample4Tile selectedTile = null; // find a tile to place the unit on. I will randomly select one. // but I need to check if there is not already a unit on the // selected tile before accepting it. while (true) { int idx = Random.Range(0, map.grid.Length); // make sure this is a valid node if (map.ValidIDX(idx)) { // now check if there is not already a unit on it selectedTile = map.grid[idx] as Sample4Tile; if (selectedTile.unit == null) { // no unit on it, lets use it break; } } } // create the unit and place it on the tile GameObject go = (GameObject)Instantiate(unitFab); go.transform.position = selectedTile.position; go.layer = 9; // in this sample Units must be in layer 9 // be sure to tell the tile that this Unit is on it Sample4Unit unit = go.GetComponent <Sample4Unit>(); unit.Resetunit(); // reset its moves now too unit.LinkWithTile(selectedTile); units.Add(unit); // keep a list of all units for quick access } }
void SpawnEnemy() { // 在六边形网格地图最右侧随机生成敌船 NavalTile sourceTile = null; while (true) { int idx = map.mapHorizontalSize * (map.mapVerticalSize - 1) + Random.Range(0, map.mapHorizontalSize); // make sure this is a valid node if (map.ValidIDX(idx)) { // now check if there is not already a unit on it sourceTile = map.grid[idx] as NavalTile; if (sourceTile.unit == null) { // no unit on it, lets use it break; } } } // create the unit and place it on the tile GameObject go = (GameObject)Instantiate(enemyFab); go.transform.position = sourceTile.position; go.layer = 9; // Units must be in layer 9 go.tag = "Enemy"; // be sure to tell the tile that this Unit is on it EnemyUnit unit = go.GetComponent <EnemyUnit> (); unit.Resetunit(); // reset its moves now too unit.LinkWithTile(sourceTile); unit.OnDeath += OnDeath; enemyList.Add(unit); // keep a list of all enemies for quick access // 设置敌船的随机目标 NavalTile targetTile = null; while (true) { int idy = map.mapHorizontalSize * 1 + Random.Range(6, map.mapHorizontalSize - 6); // set each enemy's targets if (map.ValidIDX(idy)) { targetTile = map.grid[idy] as NavalTile; if (targetTile.target == false) { targetTile.target = true; break; } } } List <MapNavNode> unitPath = map.Path <MapNavNode> (sourceTile, targetTile, OnNodeCostCallback); if (unitPath != null) { unit.Move(unitPath, null); } // 更新敌人数量 curEnemyCount++; }