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

Unity中Compute Shader报错及生命游戏纹理不更新问题

Unity生命游戏Compute Shader问题修复(Android平台 2021.3.4f1)

问题现象

运行时触发报错:

Compute shader (cs): Property (Result) at kernel index (1) is not set
UnityEngine.StackTraceUtility:ExtractStackTrace ()
CSTest:Update () (at Assets/Scripts/Pixel/CSTest.cs:43)

程序仅显示Init生成的黑白初始点,RenderTexture无法更新,CSMain函数完全未执行。

问题根源

Compute Shader的每个kernel是独立的资源上下文,你仅为Init kernel绑定了Result纹理,但CSMain kernel未关联对应的RenderTexture,导致Dispatch时触发资源未初始化错误,直接跳过CSMain执行。

同时存在一个潜在隐患:RenderTexture的Y轴尺寸为Size/2,但Dispatch时Y方向线程组计算用了Size/4,会导致线程组数量超出纹理实际尺寸,可能触发坐标越界。

修复方案

  1. 为CSMain kernel绑定Result纹理
  2. 修正Dispatch时Y方向的线程组计算逻辑,匹配RenderTexture实际尺寸

修改后的C#代码

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

public class CSTest : MonoBehaviour
{
    [SerializeField]
    Material graphBackgroundMat;

    [SerializeField]
    ComputeShader computeShader;

    [SerializeField]
    int Size = 256;
    int kernel;

    public bool Run = false;

    RenderTexture renderTexture;

    void Start()
    {
        renderTexture = new RenderTexture(Size, Size / 2, 0, RenderTextureFormat.ARGB32);
        renderTexture.enableRandomWrite = true;
        renderTexture.filterMode = FilterMode.Point;
        renderTexture.Create();

        // 初始化Init kernel并绑定纹理
        int initKernel = computeShader.FindKernel("Init");
        computeShader.SetTexture(initKernel, "Result", renderTexture);
        graphBackgroundMat.SetTexture("_MainTex", renderTexture);
        // 修正Y方向线程组计算:匹配RenderTexture实际Y尺寸
        computeShader.Dispatch(initKernel, 
            Mathf.CeilToInt(Size / 4f), 
            Mathf.CeilToInt((Size / 2f) / 4f), 
            1);

        // 关键:为CSMain kernel绑定Result纹理
        kernel = computeShader.FindKernel("CSMain");
        computeShader.SetTexture(kernel, "Result", renderTexture);
    }

    void Update()
    {
        if (Run) 
        {
            // 同步修正Y方向线程组计算
            computeShader.Dispatch(kernel, 
                Mathf.CeilToInt(Size / 4f), 
                Mathf.CeilToInt((Size / 2f) / 4f), 
                1);
        }
    }

    private void OnDestroy()
    {
        renderTexture.Release();
    }
}

额外注意事项

  • 确保Compute Shader中RWTexture2D的名称Result与C#SetTexture的参数完全一致
  • Android平台需确认设备支持Compute Shader(中高端设备普遍支持,低端设备可能存在兼容性问题)
  • 线程组大小[numthreads(4,4,1)]需与Dispatch的线程组计算逻辑匹配,避免纹理坐标越界

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:34:54