trying to optimise my script by making things global?

Hi there,
I have a bunch of scripts on each level of my game and most of them have the same bit of code in a start function.
Something like this

Character = GameObject.Find("Dude");
CharacterScript = Character.GetComponent(ChScript)as CHScript;

I was wondering, is there a way to make my character script(in this case) global and accessible to other scripts without having to to this each time? It just seems kinda wastefull that so many of my scripts have this same bit of code.
I know you can do static variables but I want to be able to alter them from other scripts.

Thanks
Pete

Sure, you can simply stick that in a public static field in any class.

Your script files don’t have to be limited to Monobehaviour implementations, you can create classes and interfaces just like any other C# application.

You can probably even do something like the following

class DudeScript : Monobehaviour
{

public static DudeScript dude;

public void Start() 
// or Awake() if you are going to reference this variable in the Start() portion of other scripts.
{
dude = this; // Assuming only one dude is ever created.
}

}

Then you would be able to reference DudeScript.dude from any script

Hey thanks!

That sounds like exactly what I’m after.
One thing though, my scripts so far are in JScript, is something like that available through JScript or is it exclusively a C# thing?

Pete

class DudeScript : System.Object
{
  static var DudeScripte dude;

  function Start()
  {
    // scripts

    dude = this;
  }
}

something like this should it be.

hmmm, still having a little trouble with this, sorry just trying to get my head around the class thing.

I get an issue with this

class DudeScript : System.Object

Unexpected token: :.

means there is an error with your System.Object
because he cannot call the Object on the System. thats why hes complaining there is a point, and just deleting that wont help x) cuz then he wont recognize SystemObject xD
there is something wrong with that class.

You don’t have to do the class declaration if you’re doing a Unity JavaScript file, Any functions you declare in the file simply become methods, and any global variable declarations just become fields of a Monobehaviour class… So it will probably be more like this:

  static var DudeScripte dude;

  function Start()
  {
    // scripts

    dude = this;
  }

But if I put it as a static var, doesn’t that mean that I can access it globally but not modify it?

No, it just means that there is only one instance of that variable, independent of how many objects you instantiate of a given class.

Anybody can edit it at any time, so it just means that you need to be careful when accessing static variables from multiple threads.