Change Color on Raycast Hit

In the process of developing the RB controller, one of the functions I wanted to incorporate was highlighting objects when hit by the raycast. This has been on the dev list for some time, so this basic prototype is well overdue.

The starting point for this functionality is this forum post:

https://answers.unity.com/questions/1112741/how-do-i-change-the-raycasthit-material-back.html

This functionality has been highlighted in a previous post about the Pick Up and Throw functionality, but one bug in the setup was related to the colors ‘sticking’ and not reverting to their original state:

Tangled up in blue – previously selected objects not reverting to their original color

Turns out the reason for this unwanted behaviour was attaching the function to the main player manager and trying to read and store color values on a case by case basis.

By moving the script on to the object itself and allowing that to check for raycast hits, the ‘sticky color’ problem has been resolved while simultaneously streamlining my logic:

  • Each ‘interactable’ object can now have bespoke color values even though they all share the same class
  • No need to compare tags as the interaction is calculated by the object
Testing color change on hit using multiple objects and colors

Heres the related code snippet in the object class – only called if the object is hit:

[Header("Colors")]
    public Color defaultColor;
    public Color highlightColor;
    public Transform previousObject = null;
    new Renderer renderer;

Start()
{
//Get the renderer component on this object:
renderer = GetComponent<Renderer>();
}

Update()
{
//is raycast hitting THIS object?
        if (playerManager.rayCastHit == this.transform)
        {
            //Check if this hit is the same as the stored hit:
            if (previousObject != this.transform)
            {
                //store hit object:
                previousObject = this.transform;

                //change hit object color:
                renderer.material.color = highlightColor;
            }
        }

        //if no raycast hit:
        else
        {
            //Reset hit object material
            renderer.material.color = defaultColor;

            //Clear reference
            previousObject = null;
        }
............
}

This basic functionality can now be extended to use a better highlighting effect by utilising Unity’s Shader Graph to produce an edge glow effect. This effect will target the material (not just the color) and offer better representation of selected objects.

I will also post about changing the Interactable Object class to a Scriptable Object that should allow these objects to be instantiated with custom data including materials/textures and bespoke UI messages/information.