Efficient way to update mesh.colors?

Hey guys,

I’m making a scene that, when a light ray hits a meshed sphere, I will need to assign a different color for that specific triangle on the mesh that was hit.

Now I got everything working, but I want to improve the performance a little bit. I notice that every time I want to change the color of a triangle on the mesh (which means I need to change 3 vertex colors), I need to do something as following:

Color[] colors = mesh.colors;
colors *= Color.White;*

colors[j] = Color.White;
colors[k] = Color.White;
mesh.colors = colors;
Assuming i, j, k are the correct indices of vertices of a triangle. I don’t like my implementation here since every time I change vertices colors, I need to: 1) copy the colors array; 2) update the array; 3) assign the colors array back. In my game, I have to CONSTANTLY update colors like that, which might slow down the performance by a lot.
Is there a more efficient way of doing this? I was hoping I can update mesh.colors in-place, but a property cannot be passed as reference in C#… Any help is appreciated! :slight_smile:
Thanks!

Yes, there are other ways to do this. First of all the complexity depends on how many mesh objects are there? if there’s just a single sphere or just a couple of spheres you can simply keep the colors array in a member variable of your script. So you can change it and reassign it at any time.

Unity now also supports a seperate SetColors method which allows you to use a generic List instead. Unfortunately they forgot to implement GetColors as well.

There’s no way around reassigning the colors to the mesh in some way. Mesh data is actually stored on the GPU, so you don’t have direct access to it. Though if you cache the array / List the overhead should be minimal.