尝试从字符串创建材质 - 不再支持

The*_*tit 4 c# unity-game-engine

错误是:

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)
Run Code Online (Sandbox Code Playgroud)

第 27 行是:

var mat = new Material(
Run Code Online (Sandbox Code Playgroud)

第 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) );
  }
}
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 5

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

public Material(Material source);
public Material(Shader shader);
Run Code Online (Sandbox Code Playgroud)

将着色器代码放在着色器文件中以供Shader.Find查找。

var mat = new Material(Shader.Find("Transparent/Diffuse"));
Run Code Online (Sandbox Code Playgroud)