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

light on/off script help

Discussion in 'Scripting' started by bobin115, Sep 8, 2014.

  1. bobin115

    bobin115

    Joined:
    Jun 4, 2013
    Posts:
    13
    hi im new to scripting and im trying to make a script so that when mouse is down light is on and when mouse up light is off. i know this is not even close but it is my attempt as im new :

    Code (JavaScript):
    1. function Update() {
    2. if (Input.GetKeyDown("Fire1")) {
    3.     if (light.enabled == true)
    4.        light.enabled = true;
    5.     }
    6.  
    7. if (Input.GetKeyup("Fire1")) {
    8.     if (light.enabled == true)
    9.         light.enabled = false;
    10.     }
    11. }
    any help would be great

    thanks
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    Well, it looks correctly. But you should have public variable 'light' for assignment.
    Add this line in the begining, and drag and drop your light gameobject to this field in the Inspector Panel of editor.
    Code (csharp):
    1. public var light : GameObject;
     
  3. bobin115

    bobin115

    Joined:
    Jun 4, 2013
    Posts:
    13
    it came up with "can't add component "light" because it doesnt exist.check that the file name and class match" how do i solve this?
     
  4. THoeppner

    THoeppner

    Joined:
    Oct 10, 2012
    Posts:
    205
    You don't need to check if the light object is enabled or not. Just test for the mouse button:

    Code (JavaScript):
    1.    
    2. function Update() {
    3.     if (Input.GetKeyDown("Fire1")) {
    4.            light.enabled = false;
    5.     }
    6.    
    7.     if (Input.GetKeyup("Fire1")) {
    8.             light.enabled = true;
    9.     }
    10. }
    11.  
     
  5. bobin115

    bobin115

    Joined:
    Jun 4, 2013
    Posts:
    13
    this didnt work man but thanks anyway
     
  6. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,353
    This method is even better as you don't need to attach it to another gameobject. Attach it to light:

    Code (JavaScript):
    1. function Update() {
    2.     if (Input.GetKeyDown("Fire1")) {
    3.            this.GetComponent(Light).enabled = true;
    4.     }
    5.  
    6.     if (Input.GetKeyUp("Fire1")) {
    7.             this.GetComponent(Light).enabled = false;
    8.     }
    9. }
    Edit: You also misspelled "GetKeyup" instead of "GetKeyUp". Capitalization is important!
     
  7. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    GetKeyDown and GetKeyUp are used with specific key names, Fire1 is not a key.
    If you want to use the inputs defined in the Input manager you should use GetButtonUp or GetButtonDown