Statically reference a compute shader

Hi shader bods,

I have a compute shader (ClosestPointShader.compute) and I want to use it in a static class. Currently, all of my compute shaders have been instantiated by making them public and then selecting them using the interface in the editor:

I want to create a static instance of this compute shader from within my class, e.g.:

public static ComputeShader closestPointShader = new ComputeShader("ClosestPointShader.compute");

This is because I want the entire class to be static (I’d like to be able to simply do Vector3 k = ClosestPoint.Closest(point, mesh);), but I can’t see how to do this. Can I have a static instance of a compute shader in Unity?

Thanks

You can’t construct a ComputeShader like this, it’s an asset that has to get compiled to your library for different platforms.

What you can do is place it in a Resources folder, and then in a static regular class script (not monobehaviour) do:

public static class StaticResourcesLoader
{
    public static ComputeShader ClosestPointShader { get; private set; }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    private static void LoadStaticAssets()
    {
        ClosestPointShader = Resources.Load<ComputeShader>("ClosestPointShader");
    }
}

That attribute added to this static method will result in this method running when your game first starts, loading the compute shader into the static variable to then be directly referenced by whatever other scripts you want through StaticResourcesLoader.ClosestPointShader

1 Like

Exactly what I was looking for, thank you Invertex!