You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MonoGame开发ECS:如何动态创建Texture2D?实例化代码不显示求解

解决MonoGame动态生成默认Texture2D的问题

你当前的代码只是创建了一个16×16的空白Texture2D对象,但没有填充任何像素数据,所以屏幕上不会显示任何内容——MonoGame不会自动为新创建的Texture2D填充纯色,必须手动设置像素值。

生成纯色默认纹理

如果需要纯色纹理,只需创建对应长度的Color数组,填充目标颜色后写入纹理即可:

if (texture == null)
{
    int width = 16;
    int height = 16;
    this.texture = new Texture2D(Globals.graphicsDevice, width, height);
    
    // 创建纯色像素数据
    Color[] pixels = new Color[width * height];
    Array.Fill(pixels, Color.Gray); // 可替换为Color.White/Black等任意颜色
    
    // 将像素数据写入纹理
    this.texture.SetData(pixels);
}

生成黑白棋盘格纹理

如果要实现棋盘格效果,遍历每个像素坐标,根据奇偶性设置颜色:

if (texture == null)
{
    int width = 16;
    int height = 16;
    this.texture = new Texture2D(Globals.graphicsDevice, width, height);
    
    Color[] pixels = new Color[width * height];
    
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            // 根据坐标计算棋盘格颜色
            bool isWhite = (x + y) % 2 == 0;
            pixels[y * width + x] = isWhite ? Color.White : Color.Black;
        }
    }
    
    this.texture.SetData(pixels);
}

额外注意

生成纹理后,确保SpriteBatch的绘制代码正确,比如:

spriteBatch.Draw(texture, new Vector2(100, 100), Color.White);

内容的提问来源于stack exchange,提问作者Muhammad Gheith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:45:54