【问题标题】:Using functions from the c# script inside the shader在着色器中使用 c# 脚本中的函数
【发布时间】:2020-05-16 22:46:54
【问题描述】:

我正在尝试编写一个片段着色器,它会根据位置给出不同的颜色。为此,我编写了一个脚本,该脚本从给定的 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);
       }
    }

我还没有写任何着色器,因为我什至不知道从哪里开始。我需要场景中所有脚本的结果总和,然后乘以着色器的颜色。

我为英语不好表示歉意

【问题讨论】:

  • 是的,有可能。你能分享一些你的代码吗?
  • @KBaker 我编辑了帖子添加代码。

标签: c# unity3d shader fragment-shader


【解决方案1】:

C# 函数在 CPU 上运行,而着色器在 GPU 上运行,因此您无法从着色器中调用 c# 函数。

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

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多