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

Unity修改颜色后Prefab不渲染问题求助

问题描述

我正在制作Tile系统,编写了函数让每隔一个Tile变色以实现棋盘格效果,但将默认白色改为其他颜色后,修改后的颜色无法显示。手动在编辑器中修改颜色无需调用Init函数即可正常生效。

Grid Manager 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridManager : MonoBehaviour
{
    [SerializeField] private int width , height;

    [SerializeField] private Tile tilePrefab;

    void Start()
    {
        GenerateGrid();
    }

    void GenerateGrid()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                var spawnedTile = Instantiate(tilePrefab , new Vector3(x , y) , Quaternion.identity);
                spawnedTile.name = $"Tile {x} {y}";

                var isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0);
                spawnedTile.Init(isOffset);
            }
        }
    }
}

Tile 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tile : MonoBehaviour
{
    [SerializeField] private Color baseColor , offsetColor;
    [SerializeField] private SpriteRenderer renderer;

    public void Init(bool isOffset)
    {
        if (isOffset)
        {
            renderer.color = offsetColor;
        }
        else
        {
            renderer.color = baseColor;
        }
    }
}

编辑器截图

Unity编辑器中Prefab修改颜色后不渲染的截图

问题排查与解决

核心原因:SpriteRenderer引用未正确赋值

最可能的问题是Tile Prefab的renderer字段没有绑定对应的SpriteRenderer组件,导致Init函数执行时无法修改SpriteRenderer的颜色——手动修改是直接操作组件,所以能生效,而代码里因为引用为空,颜色修改逻辑根本没执行。

修复步骤

  1. 打开Tile Prefab的Inspector面板
  2. 将当前GameObject上的SpriteRenderer组件拖入renderer字段,确保该字段不为空
  3. 确认baseColor和offsetColor已设置为目标颜色,保存Prefab
  4. 重新运行游戏,颜色即可正常显示

额外优化(避免手动赋值)

可以在Tile脚本中添加自动获取组件的逻辑,防止忘记赋值:

private void Awake()
{
    // 如果未手动赋值,自动获取SpriteRenderer组件
    if (renderer == null)
    {
        renderer = GetComponent<SpriteRenderer>();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:13:20