Explanation on how to use functions, variables from other files

I seem to be running deadstraight into wall after wall with trying to figure this out. Searching points me to topics that have either nothing to do with what I want, or ones that I have looked at already.

1 : How do I use variables created outside functions in another file?

2 : What is the difference and limitations of variable types (private, public, ect)

3 : How do I use functions from 1 file in another? What if they are in a different gameobject?

4: What is the difference and limitations of function types (private, public, ect)

I'm assuming you're using Javascript.

Everything in one file is in one `class`. `private` variables and functions can only be used inside that class. `public` variables and functions can be used by that class and anything that references that class.

All of your scripts are a subtype of `Component`. So like how you can do `var myRigidbody = GetComponent( "Rigidbody")`, you can do the same thing with your classes.

Once you have a reference to your custom component type, you can then call functions and access variables just like anything else.

As a basic example:

MyClass.js:

var counter : int = 0;

function DoIncrementCounter()
{
   counter += 1;
   WillNotBeAbleToCallThisExternally();
}

private function WillNotBeAbleToCallThisExternally()
{
     Debug.Log( "private function" );
}

Notice there's no `public` declaration since in Javascript everything is assumed to be `public` by default. In C# it's the opposite, where everything is assumed to be `private`.

In another script that's attached to the same game object as the above is, you can do this:

var myClass = GetComponent( "MyClass" );
var myClassCounter = myClass.counter;
myClass.DoIncrementCounter();

And that should be obvious what that does. However you won't be able to call the private function, or access private variables with a reference to your class.

If that script is on another game object, first you have to get a reference to the game object that your script is on. From there it's the same, you would just call `GetComponent` on the game object reference itself. You can search by name (bad idea, but what most people start with since it makes the most obvious sense), or you can set up references inside your script and set things up ahead of time in the scene or via instantiation.