How to find a component and disable it from another objects script?

Hey,

so how could I disable a Camera on an object when the script which disables it is in another object.

#pragma strict

var failSound : AudioClip;

function OnTriggerEnter(col : Collider)
{
	if (col.tag == "Player")
	{
		audio.PlayOneShot(failSound);
		print("Dead");
		GetComponent(Camera).enabled = false;
	}
	else
	{
		GetComponent(Camera).enabled = true;
	}
}

Like this

You can search for components with

  • FindObjectOfType<>() (if you know
    there’s only one of that type, so
    it’ll return that)
  • FindObjectsOfType<>() (to get
    multiple components of that type and search through them)

Note: Like GameObject.Find(), it is an expensive function.


Specifically, for main or any other (check the static properties in the docs linked) camera you could easily disable like this:

Camera.main.enabled = false;

This is way better (performance-wise) than FindObjectOfType<>() assuming you’re interested in camera components only.