3

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

2
  • 1
    Yes, it is possible. Could you share some of your code? Commented May 16, 2020 at 23:31
  • @KBaker I edited the post adding code to it. Commented May 17, 2020 at 8:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.