Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Easy switch Light On/Off

Discussion in 'Getting Started' started by Opacki, Dec 6, 2015.

  1. Opacki

    Opacki

    Joined:
    Sep 12, 2015
    Posts:
    10
    Hi, I want give you short code for switch light On/Off
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class LightOnOff : MonoBehaviour
    5.  
    6.     //Włącznik/Wyłącznik Światła napisany przez Opacki
    7. {
    8.     public Light light;
    9.     private bool _switch;
    10.  
    11.     void Start(){
    12.         light.enabled = false;
    13.     }
    14.  
    15.     public void Operate(){
    16.          if (_switch){
    17.             light.enabled = true;
    18.             }    
    19.         else
    20.         {
    21.             light.enabled = false;
    22.         }
    23.         _switch = !_switch;
    24.          }
    25. }
    26.  
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,206
    This is good! But it could be made simpler... you don't need a separate bool to track the list status, when light.enabled already does that. So:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class LightOnOff : MonoBehaviour
    4.     //Włącznik/Wyłącznik Światła napisany przez Opacki
    5. {
    6.     public Light light;
    7.  
    8.     public void Operate() {
    9.          light.enabled = !light.enabled;
    10.      }
    11. }
    Making Operate a public method was a great idea; it lets you trigger this switch toggle from Unity Events.
     
  3. Opacki

    Opacki

    Joined:
    Sep 12, 2015
    Posts:
    10
    Haha, Good to know are simpler way to do this :)
     
unityunity