I’m encountering a problem when calling the same ComputeShader Dispatch() on Update() for two (or more) GameObjects.
I’ve written the following code to illustrate the issue:
// Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public ComputeShader _computeShader;
public CustomRenderTexture _customRenderTexture;
public Material _material;
public Renderer _renderer;
void Start()
{
_customRenderTexture = new CustomRenderTexture(256, 256);
_customRenderTexture.enableRandomWrite = true;
_customRenderTexture.Create();
_material = new Material(Shader.Find("Standard"));
_material.mainTexture = _customRenderTexture;
_renderer = gameObject.GetComponent<Renderer>();
_renderer.material = _material;
_computeShader.SetTexture(0, "Result", _customRenderTexture);
_computeShader.SetFloats("width", _customRenderTexture.width);
_computeShader.SetFloats("height", _customRenderTexture.height);
}
void Update() {
_computeShader.SetFloats("t", Time.time % 2f);
_computeShader.Dispatch(0, _customRenderTexture.width / 8, _customRenderTexture.height / 8, 1);
}
}
// Test.compute
#pragma kernel CSMain
float width, height;
float t;
RWTexture2D<float4> Result;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
Result[id.xy] = float4(t * id.x / width, t * id.y / height, 0.0, 0.0);
}
Putting Test.cs/Test.compute on two planes has the following result:
clevertepidbetafish
The second plane receives only a black texture.
However, If I duplicate the Test.compute asset, and assign the new asset to Test.cs on the 2nd plane, I get this result:
similarbonyatlanticbluetang
Now both planes behave as expected.
Irregardless of if calling Dispatch() in Update() is bad practice or not, what am I doing wrong here? Is there a different way I should be instantiating my ComputeShader objects in my Test.cs script rather than assigning them in the inspector via a public variable? I hope there isn’t something painfully obvious that I’m missing.