As Unity does not provide triangle object, I need to create it by C#.
After adding Mesh Filter and Mesh Renderer by C#, the object cannot add such components again in scene.
I can only change the color of object created.
Now, I need to change Materials Element 0 of Mesh Renderer to a selected image as a shader.
I have tried Resources.Load () and Shader.Find () but they don’t work.
How can I do it in C#? Please explain with code.
Here is my code 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 () {
}
}