lighting click help

im am new to coding and need help with my script what im trying to do is mouse down light on and mouse up light off here is the script

function Update() {
if (Input.GetKeyDown("Fire1")) {
    if (light.enabled == true)
       light.enabled = true;
    }
 
if (Input.GetKeyup("Fire1")) {
    if (light.enabled == true)
        light.enabled = false;
    }
}

i have tried adding in this:

public var light : GameObject;

but i get this error can’t add component “light” because it doesnt exist.check that the file name and class match

that didnt work so i tried

var muzzleFlash : GameObject;
 
function Update() {
 
    if (Input.GetKeyDown("Fire1")) {
           !linkedLight.enabled = linkedLight.enabled;
    }
}

if someone could amend any my scripts and make them work that would be great

thanks

Well first of all (first if => false and GetKeyup => GetKeyUp):

function Update() {
if (Input.GetKeyDown("Fire1")) {
    if (light.enabled == false)
       light.enabled = true;
    }
 
if (Input.GetKeyUp("Fire1")) {
    if (light.enabled == true)
        light.enabled = false;
    }
}

Secondly, as Khenkel mentioned, light is already used as default, so try renaming it.
Quick tip, you can use F2 to refactor the name, so you only have to do it once and the system will apply for the rest of the script :slight_smile:

Thirdly, you can enable a “Light” component, right now you have a GameObject component, you can either deactive only the light component, or the entire gameObject.
If you want to use the “enable” on a GameObject, you should use SetActive(true); (or false)

All of the Above leads to (Possibly):

public var newNameForLight: GameObject;

function Update() {
if (Input.GetKeyDown("Fire1")) {
    if (newNameForLight.activeSelf == false)
       newNameForLight.SetActive(true);
    }
 
if (Input.GetKeyUp("Fire1")) {
    if (newNameForLight.activeSelf == true)
        newNameForLight.SetActive(false);
    }
}

OR

public var newNameForLight: Light;

function Update() {
if (Input.GetKeyDown("Fire1")) {
    if (newNameForLight.enabled == false)
       newNameForLight.enabled = true;
    }
 
if (Input.GetKeyUp("Fire1")) {
    if (newNameForLight.enabled == true)
        newNameForLight.enabled = false;
    }
}

In both cases, don’t forget to drag in the public variable :slight_smile:

Hope that helps, if I misunderstood or made grammar mistakes, my apologies :wink:

try this is simple and i think its what ur after

function Update() {
  if (Input.GetMouseButtonDown(0)) {
    light.intensity = 1;
  }
  else if (Input.GetMouseButtonUp(0)) {
    light.intensity = 0;
  }
}

Try renaming the GameObject to something else, because “light” is already used. Every GameObject has a light variable by default (doesn’t matter if it exists or not) and you’re trying to access it.

Check this for more info:

EDIT:
Also if you want to disable/enable a GameObject, you have to use obj.SetActive(true/false), because obj.enabled doesn’t work here.