- Home /
How to apply two colors to the object?
Hi all, I want to apply two colors to the cube ,half is red and half is blue. I want to do through the script or material or shader . I dont want to use textures. How i can do this ? Thanks.
Answer by Andy.... · Jun 22, 2015 at 03:43 PM
At first I can imagine 2 simple answers:
If you're using Unity's cube, put 2 of them side by side and change their colors individually
By using any modeling program, it's kinda easy to assign 2 materials to the same model, either by creating a few more vertices and changing their face materials, or by UV Mapping, which would probably lead you to work with "Texture mapping", not necessarily with real texture, just colors.
First Option i don't need, bcoz i want apply colors only one object.
Is their any option to apply gradient colors to the object ,am using unity cube itself. Thanks
Answer by Cherno · Jun 23, 2015 at 08:54 AM
You can use the Mesh class to change the cube mesh' vertex colors, and use a shader that supports vertex colors with it. This will automatically give you a smooth gradient between vertices of different color. To find out which vertices are where on the cube, you have to either use the trial and error approach, or use a simple function that displays the vertex number closest to the mouse cursor, like this one I wrote:
public void GetVertexIndices() {
Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(mouseRay, out hit, Mathf.Infinity) == true) {
if(hit.collider.gameObject.GetComponent<MeshFilter>() == null) {
Debug.Log("Hit object has no MeshFilter!");
return;
}
Mesh mesh = hit.collider.gameObject.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
int vertexIndex0 = triangles[hit.triangleIndex * 3 + 0];
int vertexIndex1 = triangles[hit.triangleIndex * 3 + 1];
int vertexIndex2 = triangles[hit.triangleIndex * 3 + 2];
Debug.Log("Indices for triangleIndex " + hit.triangleIndex + ": " + vertexIndex0 + "," + vertexIndex1 + "," + vertexIndex2);
//Debug.Log("Vertex Positions: " + vertices[vertexIndex0] + "," + vertices[vertexIndex1] + "," + vertices[vertexIndex2]);
}
}
Nice code , to show the vertex colors. Thanks.
For my issue i have to use $$anonymous$$aterial which is i created in maya ,it has two colors in one material.
In unity it is some difficult to do Half half colors.
Your answer
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
Changing two different objects renderer colour 1 Answer
Materials are colored differently on rotated objects 1 Answer
UI Triangle Color picker 0 Answers
Find HDRP Lit Shader 1 Answer