A simple light switch

Hi I am very new to scripting

So Please treat me like an idiot. I won't mind.

I just want to make a light switch on a box on a wall that when clicked with a mouse toggles of and on a light globe on a ceiling.

I have managed to figure out how to mouse click and toggle variables. But how do I send the on off command to the light script?

For that matter how do I run functions in other scripts/objects from a different object?

I have spent hours and hours searching the references and help and forum and the only answers I found may as well have been written in zulu.

WHAT I'VE DONE SO FAR.............

//Add a toggle variable for light on off call it lightState static var lightState : boolean;

function Update () {

// Make sure the user pressed the mouse down
if (!Input.GetMouseButtonDown (0))

        var hit : RaycastHit;

if (Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition),  hit, 100))


    lightState = (!lightState);
    print ("var lightstate = " + lightState);

        else {
    print ("I've clicked nothing!");





Also, is there a good book on javasript relevant to unity that I should get?

While raycasting is a very valuable thing to learn about when using unity, you could implement clickable light switches in a much simpler way. Place this script on each lightswitch object:

var linkedLight : Light;

function OnMouseDown() {
    linkedLight.enabled = !linkedLight.enabled;

That is it. Now just drag that script onto each lightswitch. Once you have that script on each lightswitch, you need to drag a reference to the corresponding light into the `"light"` variable for each switch. This creates a reference link to each switch's light.

Note that you can have more than one switch per light using this method.

For more information about how to communicate between scritps and other objects, see this answer:

Communication between objects and other scripts

try this for two lights:

#pragma strict

var linkedLight1 : Light;
var linkedLight2 : Light;

function OnMouseDown() {

 linkedLight1.enabled = !linkedLight1.enabled;
 linkedLight2.enabled = !linkedLight2.enabled;


It work!
I tested it.