Change mesh color with lightmap

Well some people may not want to use any additional lights at all to color their objects. Or some people may need a little bit extra coloring from the surrounding areas. This script will shoot a ray down and get the lightmap pixel value directly underneath the player. Very useful for the player view guns which is what the script is setup for (that’s why the player variable is an array, my gun and arms are 2 different models).

One thing to note: You have to enable Read/Write on the Lightmap textures for this to work!

Hope this helps someone.

public var player : Renderer[];
private var text: Texture2D;
private var index: int;
private var col: Color;
private var pixelUV: Vector2;

function Update () 
{
	// Only if we hit something, do we continue
	var hit2 : RaycastHit;
	var down = transform.TransformDirection (Vector3.down);
	if (!Physics.Raycast (transform.position, down, hit2, 100))
	return;

	// Just in case, also make sure the collider also has a renderer
	// material and texture. Also we should ignore primitive colliders.
	var renderer : Renderer = hit2.collider.renderer;
	var meshCollider = hit2.collider as MeshCollider;
	if (renderer == null || renderer.sharedMaterial == null ||
	renderer.sharedMaterial.mainTexture == null || meshCollider == null)
	return;

	index = renderer.lightmapIndex;
	tex = LightmapSettings.lightmaps[index].lightmapFar;

	pixelUV = hit2.lightmapCoord;
	pixelUV.x *= tex.width;
	pixelUV.y *= tex.height;

	col= tex.GetPixel(pixelUV.x, pixelUV.y);
	col = Vector4(0.8, 0.8, 0.8, 1.25) * col;
	for ( var player2 in player )
	{
		for (var mats in player2.materials)
		{
			mats.color = Vector4.Lerp(mats.color, col, Time.deltaTime * 10);
		}
	}
}

Slight update to the code to make it work with renderers that have multiple materials.

i got an error