我有一个预先创建的带有红色图块的图块。我希望能够浏览我的tilemap,并且如果一个瓦片是红色瓦片,则将其设置为蓝色瓦片。
我有以下想法
public Tile blue;
public Tile red;
但是我不确定如何遍历所有磁贴,如果磁贴为蓝色,则将其旁边的磁贴设置为红色。
有人可以给我任何建议吗?
答案 0 :(得分:0)
您可以使用foreach循环。检查每个瓷砖。如果是红色,则将其设置为蓝色。
如果您的图块存储在2d数组中,则其旁边的图块应具有当前图块的x
值+ 1。
for (int x = 0; x < gridSizeX; x++)
for (int y = 0; y < gridSizeY; y++)
if (grid[x, y].color == Color.red)
grid[x + 1, y].color = Color.blue;
答案 1 :(得分:0)
如果您已经有一个现有的tilemap,则像@ live627这样的嵌套循环将起作用。创建后是否总是要检查?因为您在生成它们的同时将它们映射为红色/蓝色。这将为您节省一些计算时间。但是,这仅适用于偶数网格。
Grid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grid : MonoBehaviour
{
public int gridSize = 10;
public Tile tilePrefab;
void Start() {
SetGrid();
}
public void SetGrid() {
int total = gridSize * gridSize;
for(int i = 0; i < total; i++) {
int posX = (int)Mathf.Floor(i/gridSize);
int posY = i % gridSize;
Tile t = Instantiate(tilePrefab).GetComponent<Tile>();
t.SetPosition(posX, posY);
if((posX + posY) % 2 == 0)
t.SetColor(Color.blue);
else
t.SetColor(Color.red);
}
}
}
Tile.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
public int X;
public int Y;
private Renderer m_Renderer;
private void Awake() {
this.m_Renderer = this.GetComponent<Renderer>();
}
public void SetPosition(int x, int y) {
this.X = x;
this.Y = y;
this.transform.position = new Vector3(x, y, 0);
}
public void SetColor(Color c) {
m_Renderer.material.color = c;
}
}
这将创建一个网格,该网格将在一维循环中为您生成类似于国际象棋的网格,而不是嵌套循环。
此特定循环:
int total = gridSize * gridSize;
for(int i = 0; i < total; i++) {
int posX = (int)Mathf.Floor(i/gridSize);
int posY = i % gridSize;
Tile t = Instantiate(tilePrefab).GetComponent<Tile>();
t.SetPosition(posX, posY);
if((posX + posY) % 2 == 0)
t.SetColor(Color.blue);
else
t.SetColor(Color.red);
}
如果您只想遍历列表而没有嵌套循环,则可以使您步入正轨。您必须将其更改为想要发生的事情。