Calling script from prefab

I have a tree stump prefab (felled_tree), and i wish to check a script located in the main camera for a variable.

var log : GameObject;
var player : GameObject;
var dist : int;
var cam : Camera;

var toollist : toollist;

var lootable : boolean = true;
var ebutton : Texture2D;
var etouse : boolean = false;

function Start () {


}

function Update () {

player = GameObject.Find("Main Camera");

cam = GameObject.Find("Main Camera").camera;

dist = Mathf.Sqrt((player.transform.position - transform.position).sqrMagnitude);

if (dist <= 2 && lootable == true){
	etouse = true;
}

if (etouse){
	if (Input.GetKeyUp("e")) {
	treesize -=1;
	SpawnLog();
	}
}


if (dist >= 2 || !lootable) {
	etouse = false;
}

if (treesize == 0) {
lootable = false;

}

}


function OnGUI() {

if (etouse) {
GUI.Label (Rect (Screen.width /2, Screen.height /2, 32, 32), ebutton);
}


}

function SpawnLog (){

Instantiate(log, transform.position, transform.rotation);

}

As you can see, i have worked out how to automatically assign the camera and player to the prefab, but i am having trouble working out how to assign a script located in a gameobject, so i can check for certain variables.

Right, I’m sorry to tell you that you are really doing that right…

  • do not call GameObject.Find in Update, certainly not every frame.
  • You get the main camera by doing Camera.main, which is much faster anyway

When you have variables like you do here, you can assign them by dragging and dropping in the inspector. Or at a push, if there was some reason why that didn’t work, you would assign them once in Start() or Awake()

When you want to get another script, and you have the game object that has that script on it (or indeed any other component on it) you get you script using

  var myScript = myGameObjectOrComponent.GetComponent(NameOfTheScriptYouWant);