I'm trying to write a fragment shader that will give a different color depending on the position. For this purpose, I wrote a script that returns the color from given vector3 and I want to call this function inside a shader. Is it possible at all?
My code:
using System.Collections.Generic;
using UnityEngine;
public class CustomLight : MonoBehaviour
{
public static List<CustomLight> lights = new List<CustomLight>();
[Min(0)]
public float intensity = 1;
public Color color = Color.white;
[Min(0)]
public float radius = 4;
[Range(0, 1)]
public float innerRadius = 0;
public Color GetLight(Vector3 point)
{
if (intensity <= 0 || radius <= 0) return Color.clear;
float value = 0;
float distanceSqr = (point - transform.position).sqrMagnitude;
if (distanceSqr >= radius * radius) return Color.clear;
if (innerRadius == 1) value = 1;
else
{
if (distanceSqr <= radius * radius * innerRadius * innerRadius) value = 1;
else value = Mathf.InverseLerp(radius, radius * innerRadius, Mathf.Sqrt(distanceSqr));
}
return color * intensity * value;
}
private void OnEnable()
{
if (!lights.Contains(this)) lights.Add(this);
}
private void OnDisable()
{
lights.Remove(this);
}
}
I haven't written any shader yet, because I don't even know where to start. I need the sum of results from all scripts on the scene, then multiply it by the color of the shader.
I apologize for poor English
C# functions run on the CPU while shaders run on the GPU, as such you can't call c# functions from a shader.
You can however access variables passed to the shaders through the materials via Material.SetX methods, which is likely the closest to what your trying to achieve.