Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions from the c# script inside the shader

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

like image 593
Max Shein Avatar asked Dec 06 '25 15:12

Max Shein


1 Answers

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.

like image 102
Zami Avatar answered Dec 08 '25 03:12

Zami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!