Unity手撸2048小游戏——自动生成4*4棋盘

1、新建文件夹,命prefabs,将刚刚做成的Chessman拖入该文件下,做成预制体

2、删除panel下的Chessman

3、在panel下,新建一个空对象,命名为Chessboard,大小设置为宽400,高400

4、为Chessboard添加GridLayoutGroup,CellSize中x和y都设置成100

5、开始撸棋盘生成的代码,新建、命名Chessboard

using UnityEngine;
using System.Collections;

public class Chessboard : MonoBehaviour {

    public GameObject prefab_chessman;            //预制体
    private GameObject [] obj_chessman;            //将要生成的游戏对象数组
    public int num_chessman = 16;                //将要生成16个对象

    private ChessMan[] script_Chessman;            //Cheesman的控制代码数组


    // Use this for initialization
    void Start () {
        obj_chessman = new GameObject[16];        //实例化对象
        script_Chessman = new ChessMan[16];        //实例化对象
        fn_startPos();                            
    }

    public void  fn_startPos(){
        for (int i = 0; i < num_chessman; i++) {
            //实例化
            obj_chessman [i] = Instantiate (prefab_chessman) as GameObject ;

            //将物体设为chessboard游戏对象的子物体
            obj_chessman [i].transform.parent = gameObject.transform;            

            //获取对象身上的ChessMan组件,并将其赋值给script_Chessman
            script_Chessman [i] = obj_chessman [i].GetComponent ();    
        }
    }
}

6、将代码加到Chessboard上

7、将预制体拖到脚本下(做的时候忘了做,写的时候忘了写,这记性也没谁了)

8、运行,成功生成。

转载于:https://www.cnblogs.com/DuYiNan/p/6179829.html

你可能感兴趣的:(Unity手撸2048小游戏——自动生成4*4棋盘)