:EDIT:
I had tried this implementation and found it was still too slow for what I need, so I used a dictionary! This is my first time really needing one, but I found that the .GetComponent<Renderer>()
was the bottleneck in the snippet from my question.
This part isn't really related to the question per se, but it's related to what I'm doing, so I figured I'd post my solution here for all the future visitors. I can skip finding the renderer, then finding the material, then finding the texture every time and just associate a texture directly with the gameObject by caching them in a Dictionary. Dictionaries are built for quick lookups and I found the following to be very, very fast (virtually no change in framerate versus without any of the texture lookup code now):
// In the class definition:
private Dictionary<GameObject, Texture2D> textureDictionary = new Dictionary<GameObject, Texture2D>();
Renderer renderer;
Material material;
Texture2D texture;
Vector2 textureCoord;
Color color;
int textureId = Shader.PropertyToID("_BumpMap");
// After running the raycasts:
// If the texture isn't in the dictionary, add it!
if (textureDictionary.TryGetValue(results[i].collider.gameObject, out texture) == false)
{
bool textureFound = false;
renderer = results[i].collider.gameObject.GetComponent<Renderer>();
if (renderer != null) // Terrain has no renderer, so need to check
{
material = renderer.sharedMaterial;
texture = (Texture2D)material.GetTexture(textureId);
if (texture != null) // We're looking for the bump map texture here, which could be null
{
textureDictionary.Add(results[i].collider.gameObject, texture);
textureFound = true;
}
}
if(textureFound == false) // If the texture doesn't exist that's fine, but put a null entry in the dictionary so you don't continue to look for it every iteration
{
texture = null;
textureDictionary.Add(results[i].collider.gameObject, texture);
}
}
if(texture!=null)
{
textureCoord = results[i].textureCoord;
color = texture.GetPixelBilinear(textureCoord.x, textureCoord.y);
// Do your stuff with the bump map color now
}
}