How do I trigger visibility of a gameObject

I am wanting to create the Diablo 3 effect of objects visibility toggling on and off when passing behind. I have this so far…

var target = gameObject;

function OnTriggerEnter() {

 // toggle visibility:
 renderer.enabled = !renderer.enabled;

}

I know this shouldn’t work, and would like to know what to do to make it work. I am using a script…

function Update() {

if (Input.GetKeyDown(KeyCode.Z))
{
// toggle visibility:
renderer.enabled = !renderer.enabled;
}
}

This works fine, but I want it to work off a trigger not a key.

OnTriggerEnter(Collider col)
{
col.gameObject.renderer.enabled = false;
}

The way you are doing it can give unpredicted results. Even the above can. You should specify by a layer or by the object. such as

if(col.gameObject.layer == 8)
col.gameObject.renderer.enabled = false;

on an even more extended note you should also preform a check with a bool isVisible!

if(col.gameObject.layer == 8 && isVisible)
{
col.gameObject.renderer.enabled = false;
isVisible = false;
}