Change Gizmo color based on layer hit

SO if anyone is interested, I wanted to change the color of the move to line based on the layer that was hit when the player clicks. I tried at first just copying the switch statement we had for processing mouse movements, but removed the the move to code and replaced it with code to change the gizmo color. I quickly realized that since this updates constantly, the gizmo color will change as soon as you move the cursor off the target, and thus the gizmo will change to match the new layer’s color, even though the player is still moving to the target.

Instead, I created a new variable of type Color, I then assign a color to this variable based on both the layer the cursor hits AND only when the mouse button is pressed. I did this through an if statement. I then assign the Gizmo color this color at the end. I guess I will just post code to make it easier to understand.

First I created a new variable private Color gizmoColor;

void OnDrawGizmos()
    {
        if (Input.GetMouseButton(0) && cameraRaycaster.currentLayerHit == Layer.Enemy) //We  only want to change the color if the player clicks the mouse button.
        {
            gizmoColor = Color.red;
        }
        else if(Input.GetMouseButton(0) && cameraRaycaster.currentLayerHit == Layer.Walkable)
        {
            gizmoColor = Color.black;
        }

        Gizmos.color = gizmoColor;
        Gizmos.DrawLine(transform.position, currentClickTarget);
        Gizmos.DrawSphere(currentClickTarget,.1f);
    }

What this now does is if the player click an enemy, the line drawn to the currentClickTarget will be red, and stay red even if the cursor is moved to a new layer unless the mouse button is clicked again. When the mouse button is clicked it will check to see what layer the currentClickTarget is in and change the color accordingly.

If you want other gizmos to NOT change color, say the sphere we used to display the walkMoveStopRadius, simply change the color of the gizmo in the line before we create the DrawWireSphere.

The way gizmo colors work, is that is changes the color for the gizmos that will be drawn NEXT.

Privacy & Terms