以前看没想过扫雷的实现,昨天看到一个帖子发的扫雷,写的很恶心,所以自己就尝试了一下,直接新建一个cs脚本复制以下代码就可以了。
先看看效果
代码:
using System.Collections.Generic;
using UnityEngine;
public class MineSweeper : MonoBehaviour
{
public static MineSweeper instance;
private GameObject prefab;
private List<MineCube> objects;
public int Row = 5;
public int Col = 5;
public int Mine = 10;
private int totalCount;
void Start()
{
instance = this;
CreatePrefab();
objects = new List<MineCube>();
}
void Create()
{
//mine总数小于格子数
if(Mine > Row*Col) {Debug.LogError("Mine's count canot more than grid's count!");return;}
totalCount = Row*Col;
//清除所有旧物体
int count = objects.Count;
for (int i = count-1; i >=0 ; i--)
{
objects[i].DoDestroy();
}
objects.Clear();
//创建物体
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col; j++)
{
CreateObject(i, j);
}
}
//创建mine
CreateMines();
//更新数据
UpdateMines();
}
void OnGUI()
{
GUI.Label(new Rect(Screen.width * 0.5f - 100, 0, 200, 30), "TotalBlock: " + Row * Col + " Mine: " + Mine);
GUI.Label(new Rect(0,0,50,30),"Row" );
string row = GUI.TextField(new Rect(50, 0, 50, 30), Row.ToString());
if (!int.T