1. Preface:

Simple Unity mini-game, cut images, generate random blocks, drag and drop to swap positions.

Only a small part of the game code is posted.

2. Material preparation

I did it simply, so I did not use too much material. I only prepared two fonts (brush and regular script), two button pictures and a jigsaw material picture (digimon).

3. Import the material and take action

4, simple UI framework wrote a minimalist UI framework:

(1) The base class only does show hide methods:

public class BasePanel : MonoBehaviour {/// <summary> /// display panel /// </summary> public void Show() {gameObject.setActive (true); } /// <summary> /// Hide panel /// </summary> public void Hide() {gameObject.setActive (false); }}Copy the code

(2) UIManger management class, made a singleton, display and hide the panel method

public class UIManger : MonoBehaviour { public static UIManger Instance; public List<BasePanel> panels = new List<BasePanel>(); private void Awake() { Instance = this; panels.AddRange(GetComponentsInChildren<BasePanel>()); } private void Start() { for (int i = 1; i < panels.Count; i++) { panels[i].Hide(); } } public T ShowPanel<T>() where T : BasePanel { T panel = panels.Find(p => p is T) as T; panel.Show(); return panel; } public T HidePanel<T>() where T : BasePanel { T panel = panels.Find(p => p is T) as T; panel.Hide(); return panel; }}Copy the code

5, home page here has a page jump, and difficulty selection, the code is not described

6. Game interface

private void Init() { gridLayoutGroup.cellSize = Vector2.one * (1000 - 5 * (size - 1)) / size; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { if ((i - 1) * size + j > grids.Count) { grids.Add(Instantiate(gridPrefab, gridLayoutGroup.transform)); } else { grids[i].gameObject.SetActive(true); } grids[(i - 1) * size + j - 1].SetInf(this, size, new Vector2(i, j)); } } if (grids.Count > size * size) { for (int i = size * size; i < grids.Count; i++) { grids[i].gameObject.SetActive(false); }}}Copy the code

Here, we use Layout, which automatically arranges the child objects from bottom to top and from left to right, because the UV Rect of RawImage is the coordinate system.

Two for loops generate m by m cells.

The following is a random position adjustment:

public void RandomList() { for (int i = 0; i < grids.Count; i++) { grids[i].transform.SetSiblingIndex(Random.Range(0, size * size)); }}Copy the code

Drag to swap positions, using IBeginDragHandler, IDragHandler, IEndDragHandler interface, drag after the SetSiblingIndex method to swap positions. Speaking of here this jigsaw puzzle hand swims part of the code to send so much yo!