[SOLVED, Thx Eric!] Where to put "GameObject.Find"

This page:

says “For performance reasons it is recommended to not use this function every frame Instead cache the result in a member variable at startup or use GameObject.FindWithTag.”

However, when I use code like this:

function Start(){
	var shopper = GameObject.Find("Shopper");
}

function OnGUI () {
	var cont : CCShopper = shopper.GetComponent (CCShopper);
}

I get the error:
Assets/Scripts/Shopper/ShopperGui.js(12,32): BCE0005: Unknown identifier: ‘shopper’.

What’s a poor boy to do?

Hi Vimalakirti, I might be wrong but I think this will work:

function Start(){
       var findString = "Shopper";
	var shopper = GameObject.Find(findString);
}

Give it a try, but I’m an eternalnoob so it may not help :slight_smile:

The problem is that you’ve made “shopper” a local variable to the Start function, so it can’t be accessed outside it.

–Eric

Doh!

So write it like this:

function Start(){
   public var shopper = GameObject.Find("Shopper");
}

Actually I don’t think that works; this does though:

private var shopper : GameObject;

function Start() { 
   shopper = GameObject.Find("Shopper"); 
}

–Eric

private var shopper: GameObject;

function Start(){ 
   shopper = GameObject.Find("Shopper"); 
  var cont : CCShopper = shopper.GetComponent (CCShopper); 
} 

function OnGUI() {
GuiLayout.Label(cont.whatever);

You only want to to use the find functions at script startup or when you instance a new object. Having the calls inside Update or OnGUI will not be pretty. Cache the references, then use them within your OnGUI()

Oh, I see. It doesn’t need to be declared public.

When you declare variables at the beginning of a script as ‘private’ then all functions within that script have access to the variable.

When you declare it as ‘public’ then all functions in all scripts have access to that variable.

It makes no difference in terms of what functions have access to the variable. If they’re outside any function they’re available to the entire class.

What it does control, is whether or not you can see the variable in the inspector or not.