• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by code-blep · Aug 26, 2013 at 07:43 PM · meshcolorruntimeverticestriangle

Change color of mesh triangle based on Y position in world space

Hi,

I have a mesh that I am trying to dynamically change the colors of the triangles based on their Y position in world space. I know that I have to apply the same color to the 3 vertices that make up a triangle, so that it is one solid color.

I've only just started working directly with meshes and made some progress, but the next stage is causing me problems.

How can I go through the whole mesh and apply to correct color to the 3 vertices so that each triangle is one solid color? The code below seems to get 'out of sequence' as triangle vertices have various colors applied:

 function MeshDetails(){
     meshFilter = gameObject.GetComponent(MeshFilter);
     
     mesh = meshFilter.mesh;
     vertices = mesh.vertices;
     vertexColors = mesh.colors;
     
     MeshDetailsGathered = true;
 }
 
 //-------------------------------------------------------------------------------------------------------
 //-------------------------------------------------------------------------------------------------------
 
 function ChangeColors()
 {
     
     //Iterate through vertices
     for(var i : int = 0; i <= vertices.Length - 3; ++i) //-3 as otherwise I get out of index errors
     {
 
         mesh.colors = vertexColors;
         //If vertices count matches the index (Triangle) number
         if(i == i){
             
             //Calculate Average Position for future color allocation
             //TransformPoint transforms a point from local coordinates to world coordinates wit respect to the transforms position/rotation/scale.
             var p1 : Vector3 = transform.TransformPoint(vertices[i]);
             var p2 : Vector3 = transform.TransformPoint(vertices[i+1]);
             var p3 : Vector3 = transform.TransformPoint(vertices[i+2]);
             
             //Calculate Center point
             var middlePositon = (p1 + p2 + p3) / 3;
             
             //Add Position to Debug list
             averagePositionsOfTriangles.Add(middlePositon);
 
             //Check positions and apply colors            
             if(middlePositon.y < level1Position){
                 //Apply new color and count up each time to fill the vertex range which makes up the triangle
                 vertexColors[i] = level1Color;
                 vertexColors[i+1] = level1Color;
                 vertexColors[i+2] = level1Color;
             }
              
             if(middlePositon.y > level1Position && middlePositon.y < level2Position){
                 //Apply new color and count up each time to fill the vertex range which makes up the triangle
                 vertexColors[i] = level2Color;
                 vertexColors[i+1] = level2Color;
                 vertexColors[i+2] = level2Color;
             }             
 
             if(middlePositon.y > level2Position && middlePositon.y < level3Position){
                 //Apply new color and count up each time to fill the vertex range which makes up the triangle
                 vertexColors[i] = level3Color;
                 vertexColors[i+1] = level3Color;
                 vertexColors[i+2] = level3Color;
             }              
 
             if(middlePositon.y > level3Position && middlePositon.y < level4Position){
                 //Apply new color and count up each time to fill the vertex range which makes up the triangle
                 vertexColors[i] = level4Color;
                 vertexColors[i+1] = level4Color;
                 vertexColors[i+2] = level4Color;
             } 
             
             if(middlePositon.y > level5Position){
                 //Apply new color and count up each time to fill the vertex range which makes up the triangle
                 vertexColors[i] = level5Color;
                 vertexColors[i+1] = level5Color;
                 vertexColors[i+2] = level5Color;
             }   
 
         }
     }
     
     //Update the vertex colors
     mesh.colors = vertexColors;
     
     //Sort array function
     averagePositionsOfTriangles.Sort(ByVector2Y);
     
     //Get Y min and max values
     maxYpositionUsed = averagePositionsOfTriangles[1].y;
     minYPOsitionUsed = averagePositionsOfTriangles[averagePositionsOfTriangles.Count-1].y;
 }

By the way I have rebuilt the mesh so that each triangle has unique vertices for the low-poly look

Am I at least on the right track?

Any suggestions are welcome!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by robertbu · Aug 26, 2013 at 08:02 PM

Your approach looks like it will work, but you have an errors line 23:

   if(i == i){

That's always going to evaluate to 'true'. I recommend you change your 'for' loop as follows:

 for(var i : int = 0; i <= vertices.Length - 3; i = i + 3)

This will then count by 3s. Remove the if '(i == i)'.

There is also a minor hole in your 'if' logic in that (uncommon) situation where a value is exactly on a boundary, you won't set the color. Add some '

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Aug 26, 2013 at 08:30 PM 0
Share

FYI: Vertex colors only work with a shader that supports vertex colors.

avatar image code-blep · Aug 26, 2013 at 08:33 PM 0
Share

Great points robertbu! The counting by 3 in a for loop kept tripping me up. Very useful! The code now works, although in the editor movement is quite jerky now compared to the original script I posted, which is odd. Any ideas?

avatar image robertbu · Aug 26, 2013 at 08:37 PM 0
Share

No specific ideas. Is the jerkiness due to a frame rate drop or something else?

avatar image code-blep · Aug 26, 2013 at 08:40 PM 0
Share

Framerate is good +150 fps. What is weird is if I go into the scene view after allocating the colors, do a quick camera movement, and go back into the game window, the movement is fine. It also compiles and runs fine as an exe.

Also if I remove the script after the color change, the movement is normal. I think the script is still in some kind of loop, Will start debugging and mark the question as answered.

Thanks!

avatar image code-blep · Aug 26, 2013 at 09:53 PM 0
Share

Found the problem. The array sort at the end is having to do a lot more work, will find another way to get the numbers I need.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

15 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Split single triangle mesh into 2 Equal Parts 0 Answers

Changing Mesh Vertex Colors in editor 0 Answers

Run Time Plastic Shrink/Wrap , Mesh Manipulation 0 Answers

Get average color of the texture assigned to a mesh triangle 2 Answers

Runtime mesh generation 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges