Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a material from string - this is no longer supported

Tags:

c#

unity3d

The error is:

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)

Line 27 is:

var mat = new Material(

And line 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) );
  }
}
like image 580
TheLost Lostit Avatar asked Feb 07 '23 01:02

TheLost Lostit


2 Answers

The Material string constructor is now obsolete. You can use the Shader or Material constructor.

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

Put the shader code in a shader file the use Shader.Find to find it.

var mat = new Material(Shader.Find("Transparent/Diffuse"));
like image 168
Programmer Avatar answered Feb 08 '23 14:02

Programmer


I believe there's no way to create a Material from shader strings in newer versions of Unity (which is arguably good thing).

You will need to create a Shader asset and put your code from CreateLineMaterial there. Then you can write something like:

    var mat = new Material(Shader.Find("Lines/Colored Blended"));

instead in the Material constructor.

like image 32
Gasper Avatar answered Feb 08 '23 16:02

Gasper