c# - 尝试从字符串创建 Material - 这不再受支持

标签 c# unity3d

错误是:

Trying to create a material from string - this is no longer supported.
UnityEngine.Material:.ctor(String)
Drawer:CreateLineMaterial() (at Assets/Flying Birds/Scripts/Drawer.cs:27)
Drawer:Awake() (at Assets/Flying Birds/Scripts/Drawer.cs:46)

第 27 行是:

var mat = new Material(

第 46 行:

lineMaterial = CreateLineMaterial();

using System;
using UnityEngine;
using System.Collections.Generic;

public class Drawer: MonoBehaviour
{
  public Material lineMaterial;

  struct Line
  {
    public Vector3 from;
    public Vector3 to;
    public Color color;

    public Line( Vector3 from, Vector3 to, Color color )
    {
      this.from = from;
      this.to = to;
      this.color = color;
    }
  }

  static List<Line> lines = new List<Line>();

  static Material CreateLineMaterial()
  {
    var mat = new Material(
       @"Shader ""Lines/Colored Blended"" {
       SubShader { Pass {
           Blend SrcAlpha OneMinusSrcAlpha
           ZWrite Off Cull Off Fog { Mode Off }
           BindChannels {
             Bind ""vertex"", vertex Bind ""color"", color }
       }}}"
    );

    mat.hideFlags = HideFlags.HideAndDontSave;
    mat.shader.hideFlags = HideFlags.HideAndDontSave;

    return mat;
  }

  void Awake()
  {
    if( lineMaterial == null )
      lineMaterial = CreateLineMaterial();
  }

  void OnPostRender()
  {
    lineMaterial.SetPass( 0 );

    GL.Begin( GL.LINES );

      foreach( var l in lines )
      {
        GL.Color( l.color );
        GL.Vertex3( l.from.x, l.from.y, l.from.z );
        GL.Vertex3( l.to.x, l.to.y, l.to.z  );
      }

    GL.End();
  }

  void FixedUpdate()
  {
    lines.Clear();
  }

  public static void DrawLine( Vector3 from, Vector3 to, Color color )
  {
    lines.Add( new Line(from, to, color) );
  }

  public static void DrawRay( Vector3 from, Vector3 to, Color color )
  {
    lines.Add( new Line(from, from + to, color) );
  }
}

最佳答案

Material 字符串构造函数现已过时。您可以使用着色器或 Material 构造函数。

public Material(Material source);
public Material(Shader shader);

将着色器代码放入着色器文件中,然后使用 Shader.Find 找到它。

var mat = new Material(Shader.Find("Transparent/Diffuse"));

关于c# - 尝试从字符串创建 Material - 这不再受支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39709867/

相关文章:

c# - 编译后创建继承

ios - 为什么这个iOS应用无法访问网络?

c# - 使用 Json.NET 序列化器对某些属性进行驼峰式大小写,但对其他属性不进行驼峰式大小写

c# - 使用 Unity 5 UI 进行双指缩放

c# - .NET 5 vNext 使用参数解决依赖关系

c# - 同一模式下的两个同名属性。尝试检索属性值时出错

c# - 为 Android 开发时,如何在 Unity 中动态更改网格布局组组件的单元格大小?

c# - 不知道如何在 Unity3D 中使用协程

c# - 为什么这不起作用?

c# - 在 C# 和 C++ 中使用嵌套类 - 为什么以及何时?