Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在着色器中使用c#脚本中的函数_C#_Unity3d_Shader_Fragment Shader - Fatal编程技术网

在着色器中使用c#脚本中的函数

在着色器中使用c#脚本中的函数,c#,unity3d,shader,fragment-shader,C#,Unity3d,Shader,Fragment Shader,我正在尝试编写一个片段着色器,它将根据位置提供不同的颜色。为此,我编写了一个脚本,从给定的vector3返回颜色,我想在着色器中调用这个函数。有可能吗 我的代码: using System.Collections.Generic; using UnityEngine; public class CustomLight : MonoBehaviour { public static List<CustomLight> lights = ne

我正在尝试编写一个片段着色器,它将根据位置提供不同的颜色。为此,我编写了一个脚本,从给定的vector3返回颜色,我想在着色器中调用这个函数。有可能吗

我的代码:

    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);
       }
    }
使用System.Collections.Generic;
使用UnityEngine;
公共类CustomLight:单一行为
{
公共静态列表灯=新列表();
[最低(0)]
公众漂浮强度=1;
公共颜色=Color.white;
[最低(0)]
公共浮动半径=4;
[范围(0,1)]
公共浮动内半径=0;
公共颜色GetLight(矢量3点)
{
if(intensityC#函数在CPU上运行,而着色器在GPU上运行,因此不能从着色器调用C#函数


但是,您可以通过Material.SetX方法访问通过材质传递给着色器的变量,这可能是最接近您尝试实现的方法。

是的,这是可能的。您可以共享一些代码吗?@KBaker我编辑了添加代码后的内容。