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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Unity light switch script (beginner)?

Discussion in 'Scripting' started by Mechanics55, Jul 27, 2015.

  1. Mechanics55

    Mechanics55

    Joined:
    Jul 27, 2015
    Posts:
    14
    I am a beginner to scripting in Unity, and I need some help. I have this piece of code here:

    Code (CSharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using System.Collections;
    6.  
    7. [RequireComponent(typeof(AudioSource))]
    8.  
    9. public class LightSwitch : MonoBehaviour {
    10.  
    11.     public string myString;
    12.     public Text myText;
    13.     public float fadeTime;
    14.     public bool displayInfo;
    15.  
    16.     public GameObject lightSwitch;
    17.    
    18.     public AudioClip switchOn;
    19.     public AudioClip switchOff;
    20.    
    21.     private AudioSource _audioSource;
    22.    
    23.     void Awake ()
    24.     {
    25.         _audioSource = gameObject.GetComponentInChildren<AudioSource>();
    26.     }
    27.  
    28.     // Use this for initialization
    29.     void Start () {
    30.         myText = GameObject.Find("Text").GetComponent<Text>();
    31.         myText.color = Color.clear;
    32.     }
    33.    
    34.     // Update is called once per frame
    35.     void Update () {
    36.         FadeText ();
    37.     }
    38.    
    39.     [B]void OnMouseOver ()
    40.     {
    41.         displayInfo = true;
    42.         if (Input.GetKeyDown(KeyCode.E)) {
    43.             lightSwitch.SetActive(false);
    44.             _audioSource.Play ();
    45.         }[/B]
    46.     }
    I have more code below this but it isn't relevant to my question. Anyways, I have two light gameobjects that are children of an Empty I called "Switch". Since I can't use a gameobject as a boolean, I used SetActive instead. So, my question is if there's a way for me to press "E" to toggle my lights on and off. I am able to turn them off with the code I have now, but what is the best way to go about turning them off and on as if I had a boolean doing the work for me. Please excuse my ignorance on this matter, I'm just a beginner scripter, gotta start somewhere :). The "OnMouseOver" code is really the main place I need help.
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Code (csharp):
    1. lightSwitch.SetActive(!lightSwitch.activeSelf);
    or "activeInHierarchy" instead of "activeSelf"- there is a difference between the two in that the former will show as inactive if the parent, grandparent, etc... is inactive. In other words, it's "is it showing up in the scene right now", whereas the latter will only show if the object in particular, without taking parents into account, is set to active.
     
  3. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    GameObject's have the activeInHierarchy property to test if they're active or not, so you can use that as your boolean.

    Code (csharp):
    1.  
    2. if (Input.GetKeyDown(KeyCode.E))
    3. {
    4.     if(lightSwitch.activeInHierarchy == true)
    5.         lightSwitch.SetActive(false);
    6.     else
    7.         lightSwitch.SetAtive(true);
    8.  
    9.     _audioSource.Play();
    10. }
    11.  
    EDIT: @Lysander - I guess you can ninja one :mad:
     
    a169342 likes this.
  4. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    @GroZZleR Score! ^_^

    I win more because I used the direct "flip" method rather than a conditional statement IMO ^_~. Neither of us used the conditional operator though, which makes me a bit sad, because it's a fantastically horrid way to code and everyone should know about it.
     
    GroZZleR likes this.
  5. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    For anyone who's curious, the conditional operator would be:
    Code (csharp):
    1. lightSwitch.SetActive(lightSwitch.activeInHierarchy == true ? false : true);
    or something. If you ever find yourself in need of such a thing, you're wrong- just don't do it.
     
  6. Mechanics55

    Mechanics55

    Joined:
    Jul 27, 2015
    Posts:
    14
    Works perfectly. Didn't realize it was that simple, lol :). Any recommendations on how to limit my light switch distance? I can literally switch it on and off across a building. Don't give me the code, I need to learn on my own, but any hints would be great!
     
  7. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    It would likely use a collider (a sphere collider attached to the light switch object, for instance) that the character can enter, and the OnCollisionStay function that runs every frame (like an update) that the player is inside of that collider. You can put the input code completely inside of the OnCollisionStay function, or you you can make it so that a boolean value is switched on in OnCollisionEnter and switched off in OnCollisionExit, and the bool has to be "true" to allow the input to do anything in your current script.

    Just be sure to run a tag-check (check out the Collision parameter that you get automatically in those functions) when the collision events trigger, so that for instance some random object in the scene being in range isn't setting it off every frame.
     
  8. Mechanics55

    Mechanics55

    Joined:
    Jul 27, 2015
    Posts:
    14
    Code (CSharp):
    1.  
    I've tried using OnTriggerEnter. Here's the code:

    using UnityEngine;
    using System.Collections;

    public class switchDistance : MonoBehaviour {
    public LightSwitch _lightSwitch;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void OnTriggerEnter (Collider col)
    {
    if (col.tag == "Player")
    {

    }

    else
    {
    _lightSwitch.displayInfo = false;
    _lightSwitch.lightSwitch.SetActive(true);
    _lightSwitch._audioSource.enabled = false;
    }
    }
    }

    Now, the issue is is that it's opposite of what I want. It only works when I am inside of the collider (when I'm within the vicinity of where I wish to actually turn on the light). If I'm out of range it works as usual. Any ideas on how to fix this? By the way, I created a new script and attached this to my Player character gameobject.
     
  9. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    You need to put the script on the light, not on the player, along with a collider component. Also change it so that the switch stuff happens if the col.tag IS Player, not if it ISN'T, that way only the player will be able to trigger it. You also need to make an "OnTriggerExit(Collider col)" underneath for turning it off, if your goal is that it's always on when the player is in proximity.

    You can put the entire "if(press E)" stuff from the earlier post inside of the "if(tag is player) conditional and change OnTriggerEnter to OnTriggerStay instead, if you want the player to have to hit a button to activate the light.
     
  10. Mechanics55

    Mechanics55

    Joined:
    Jul 27, 2015
    Posts:
    14
    Ah. I am thinking my issue was because I used the actual Light Switch collider? I created an empty collider and used this script and it works perfectly now, thanks! By the way, I put the code in "else" because if the Player didn't touch the collider then I wanted the OnMouseOver method to not work as programmed, so I hard coded how the lights performed.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class switchDistance : MonoBehaviour {
    5.     public LightSwitch _lightSwitch;
    6.     // Use this for initialization
    7.     void Start () {
    8.    
    9.     }
    10.    
    11.     // Update is called once per frame
    12.     void OnTriggerEnter (Collider other)
    13.     {
    14.         if (other.tag == "Player")
    15.         {
    16.             _lightSwitch.OnMouseOver ();
    17.         }
    18.        
    19.         else
    20.         {
    21.             _lightSwitch.displayInfo = false;
    22.             _lightSwitch.lightSwitch.SetActive(true);
    23.             _lightSwitch._audioSource.enabled = false;
    24.         }
    25.     }
    26. }
     
  11. markmozza

    markmozza

    Joined:
    Oct 16, 2015
    Posts:
    85
    Tutorial Light Switch with Multiple Lights