使用不同颜色的 material 绘制网格

Draw mesh using material with different colors

我正在制作一个基于网格的游戏。为此,我需要调试某些图块,例如发生碰撞的位置和玩家瞄准的位置。我制作了一个调试器 class,它使用颜色在某个位置绘制方形网格。

public class GridDebugger : MonoBehaviour {

    [SerializeField] private float alpha;

    private Mesh mesh;
    private Material mat;

    void Start() {
        mat = new Material(Shader.Find("Sprites/Default"));
        mesh = new Mesh();
        mesh.vertices = new Vector3[] { new Vector3(.5f, .5f, 0), new Vector3(.5f, -.5f), new Vector3(-.5f, -.5f), new Vector3(-.5f, .5f) };
        mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
    }

    public void Debug(Vector3 position, Color color) {
        color.a = alpha;
        mat.color = color;
        Graphics.DrawMesh(mesh, position, Quaternion.identity, mat, 0);
    }
}

目前 class 有两个用户:

[RequireComponent(typeof(GridDebugger))]
public class CollisionSystem : GridSystem {
    private List<Node>[,] grid;
    private GridDebugger debugger;

    void Awake() {
        debugger = GetComponent<GridDebugger>();
    }

    //Logic....

    void Update() {
        if (grid != null) {
            for (int x = 0; x < grid.GetLength(0); x++) {
                for (int y = 0; y < grid.GetLength(1); y++) {
                    if (grid[x, y] != null) {
                        for (int i = 0; i < grid[x, y].Count; i++) {
                            if (grid[x,y][i].Parent.Debug) {
                                Vector3 worldPos = GridToWorldPos(new Vector2Int(x, y), grid.GetLength(0), grid.GetLength(1));
                                worldPos.z = -0.0001f;
                                debugger.Debug(worldPos, Color.Red);
                            }
                        }
                    }
                }
            }
        }
    }     
}

public class GridMeleeWeapon : MonoBehaviour {
    private GridDebugger debugger;

    void Awake() {
        debugger = FindObjectOfType<GridDebugger>();
    }    

    public void Aim(Vector2 dir) {
        Vector3 position = transform.position + dir;
        debugger.Debug(position, Color.blue);                 
    }
}

CollisionSystem中,我循环每个对撞机并在每个位置绘制一个红色方块。 在 GridMeleeWeapon 中,我只是在玩家瞄准的地方画了一个蓝色方块。

问题是每个正方形都是用 CollisionSystem 中使用的颜色绘制的,即红色。在 GridMeleeWeapon 中绘制蓝色方块时,它们会变成红色。如果我在 CollisionSystem 中删除 debugger.Debug(worldPos, Color.Red),我从 GridMeleeWeapon 绘制的方块将显示为蓝色。

使用当前代码,我似乎无法绘制不同颜色的网格。我认为正在发生的事情是第一个调用者指定的颜色用于连续调用,即使 material 的颜色已更改但我不知道为什么。

如何正确设置颜色?

Material在Unity 3D中是引用类型

您在 GridMeleeWeaponCollisionSystem 中的代码使用 GridDebugger 和 material 的相同实例。发生的事情是,由于您更改了 material 颜色 OnUpdate(),它会立即(每一帧)使用此 material 将每个对象的颜色从蓝色更改为红色。

不是将颜色传递给您的 debugger().Debug() 方法,而是传递具有不同颜色的 material。例如,创建一个红色的 material 和另一个蓝色的 material。使用这些 material 设置颜色。