Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Highlight 3D objects

Discussion in 'Scripting' started by Deivydas4, Sep 20, 2023.

  1. Deivydas4

    Deivydas4

    Joined:
    Oct 28, 2021
    Posts:
    16
    Hello, Unity community!

    How can I make an object change its emission to green when I hover my mouse over it, and ensure that it stays selected (green) even after I click it? Does anyone know how to achieve this?

    Code (CSharp):
    1. public class Interaction : MonoBehaviour
    2. {
    3.     [SerializeField] private Renderer rend;
    4.     private Color color = new Color32(31, 103, 39, 255);
    5.     private List<Material> materials;
    6.     bool isHighlighted;
    7.  
    8.     private void Awake()
    9.     {
    10.         materials = new List<Material>();
    11.         materials.AddRange(rend.materials);
    12.     }
    13.  
    14.     public void ToggleHighlight(bool value)
    15.     {
    16.         if (value)
    17.         {
    18.             foreach (var mat in materials)
    19.             {
    20.                 mat.EnableKeyword("_EMISSION");
    21.                 mat.SetColor("_EmissionColor", color * 1);
    22.             }
    23.         }
    24.         else
    25.         {
    26.             foreach (var mat in materials)
    27.             {
    28.                 mat.DisableKeyword("_EMISSION");
    29.             }
    30.         }
    31.     }
    32.  
    33.     private void OnMouseEnter()
    34.     {
    35.         ToggleHighlight(true);
    36.     }
    37.  
    38.     private void OnMouseExit()
    39.     {
    40.         ToggleHighlight(false);
    41.     }
    42. }
    Thank you!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,560