Accessing other scripts is so confusing..How?

Hi,
To me the most difficult part of unity…really is to make gameobjects and script talk to each other. It should be much easier. Anyway

Q.1) I did exactly what the Unity reference says:

function Update () {    
var script:scriptname = GetComponent(scriptname);    
if (Input.GetKeyDown("space")){    	
	scriptname.Something();    	
	}
}

I have this script attached to a gameobject. The scriptname.js is attached to another gameobject in scene that by the way it’s a prefab. I get the usual (and rather annoying) “Object reference not set to an instance of an object…” What’s wrong?

Q.2) I have a whole bunch of objects in scene with the same script attached to them (scriptA). The script has allready a variable of GameObject type. That GameObject has a script (scriptB) to which I want script A to talk to and I don’t want to sit down and do this draging and dropping in the inspector. It will take much time.

Thanks in advance for your help.

Well, the first problem i see is that you're not using the variable you created. You're using the actual class name (scriptname).

Assuming that's just pseudocode and not the actual code you're using, you could be running into a problem with scope. You're simply calling GetComponent(scriptname), which will only look for a script with that name on the current game object.. the one that you're running this script from. You need to get a reference to the other game object first, which means you'd need to do something like this:

GameObject.Find("gameobjectName").transform.GetComponent(scriptname);

That's how you'd do it in C# anyway.. the syntax for JS should be very similar if not identical.

As a side note- you almost never want to use GetComponent in Update. It can be a framerate killer if you're not careful.. if you're doing something so often that it gets used in every frame, you will want to cache the reference in Awake or Start first, and then use the reference in Update.

Something like this (just winging javascript here, it may not be 100% accurate):

var script:scriptname;

function Awake() {
    script = GameObject.Find("gameobjectName").transform.GetComponent(scriptname);
}

function Update() {
    script.DoStuff();
}

var myObject : GameObject;
var objectScript : myScript;
function Start()
{
objectScript=myObject.GetComponent(myScript);
objectScript.doStuff();
}

No need for the .transform.