将网格渲染器的材质元素0更改为选定图像作为着色器

时间:2017-07-28 06:17:51

标签: c# image shader mesh renderer

由于Unity不提供三角形对象,我需要通过C#创建它。

通过C#添加网格过滤器和网格渲染器后,对象无法在场景中再次添加此类组件。

我只能更改创建的对象的颜色。

现在,我需要将网格渲染器的材质元素0更改为选定图像作为着色器。

我已经尝试过Resources.Load()和Shader.Find()但是他们不能工作。

我怎样才能在C#中做到这一点?请用代码解释。

这是我的代码triangle.cs

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

public class triangle : MonoBehaviour {
    public Vector3 center;
    public float x1, y1, x2, y2, radius;
    public string color;

    // Use this for initialization
    void Start () {
        gameObject.AddComponent<MeshFilter>();
        gameObject.AddComponent<MeshRenderer>();
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        Material mat = GetComponent<Renderer>().material;
        SphereCollider sc = gameObject.AddComponent(typeof(SphereCollider)) as SphereCollider;
        sc.center = center;
        sc.radius = radius;
        mesh.Clear();

        // make changes to the Mesh by creating arrays which contain the new values
        mesh.vertices = new Vector3[] {new Vector3(0, 0, 0), new Vector3(x1, y1, 0), new Vector3(x2, y2, 0)};
        mesh.uv = new Vector2[] {new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1)};
        mesh.triangles =  new int[] {0, 1, 2};
        switch (color) {
            case "black": mat.color = new Color (0, 0, 0, 1);  break;
            case "blue": mat.color = new Color (0, 0, 255, 1);  break;
            case "clear": mat.color = new Color (0, 0, 0, 0);  break;
            case "cyan": mat.color = new Color (0, 255, 255, 1);  break;
            case "green": mat.color = new Color (0, 255, 0, 1);  break;
            case "magenta": mat.color = new Color (255, 0, 255, 1);  break;
            case "purple": mat.color = new Color (1, 0, 1, 1);  break;
            case "red": mat.color = new Color (255, 0, 0, 1);  break;
            case "white": mat.color = new Color (255, 255, 255, 1);  break;
            case "yellow": mat.color = new Color (255, 255, 0, 1);  break;
        }
    }

    // Update is called once per frame
    void Update () {

    }
}

0 个答案:

没有答案