Advice on static variables and object references

Hi all, just a bit of advice needed here.

I am coding in C# and as my game is growing, I am adding many scripts to the myriad of game objects, but often they need to access scripts assigned to players, enemies etc.

So, simply put I am often re-typing the same code over and over in each script, namely the ones that reference player functionality.

An example would be the players control scripts and animator components.

I am forever having to remember to include the following sorts of code

// Declaring the var

GameObject player;
Animator anim;

// Then instantiating

player = GameObject.FindObjectWithTag("Player");
anim = player.GetComponent<Animator>();

Then I have to do this for each function, script etc.

Now, I don’t mind this, but it seems a little inefficient to me.

So, should I be putting these in one sort of control script that defines these as public statics so that I can reference them in a much simpler fashion?

I have never used statics before, so I am just after advice and opinions please :slight_smile:

You can have a script, that is singleton instead of static, and this way, it’s much easier for other scripts to talk to it, and the other way around.

A singleton implemntation is avaiable widely and I highly suggest you read about.

Here is what I do, I have lots of scripts that are singleton (Means, they’re available only one, not more) and some of them, I use the DoNotDestroyOnLoad methode, which does make this script not get destroyed when even loading any new level …

Let’s say a GameController (I have also SoundEffectsController, … etc and properly lots of conrtoller)

The player code can talk to GameController script without using the find methode at all

in my player start methode for example I do this

//Singleton have a variable called instance, which can call that sinleton and access the controller
GameController.Instace.player = this.gameObject;

//now on other scripts, they can access the player without doing any GameObject.Find at all

GameController.Instance.player.GetComponenet<Example>().DoThis();

as well, in my game controller, I tent to save lists of other objects, so I can access them easily, like a list of enemies, a list of NPCs or just anything!

I barely have to use GameObject.Find

and if I ever use the find methode, I usually find myself using transform.FindChild() which finds the child of that transform, not searching through all GameObjects!

Hope this helps.

Singleton for Unity3D C#: http://wiki.unity3d.com/index.php/Singleton

Best of luck!