Global classes? and access

Hi all,

Ive got quite a few single instance global classes (scripts) attached to single instantiated gameobjects.
Say C_Map,C_Player,C_Camera,C_FileManager etc
Theres a few more than this and most of them need to hold a pointer to each other for general access throughout the game.
Atm im just setting up component pointers in each of them and assigning those pointers to the correct script instances on startup.
This works fine, but it seems like im adding alot of pointers to each class to reference each class.
Is there a better way to do this?

I could have 1 new ‘holder’ class/gameobject that itself maintains pointers to the key objects and then any object that needs them would jsut have to keep a pointer to that holder class?

I know you can use static classes, where you can access themdirectly without a gameobject component search, but with a static class you cant assign stuff inthe inspector can you?

Im pretty sure there must be a more elegant way to manage the situation, any tips?

thanks

Tom

You need to look into the singleton pattern, basically you instantiate your object once and then hold a static reference to it in your class. From then on everything in your program can access this static instance. Take note that only the instance is static, so you can still modify everything in the instance as if you’ve just got it through a GetComponent call.

To give your player class as an example you’d need to put in this code (assuming you’re using C#):

//Set up a static autoproperty called instance (you could just set it up as a normal variable and have a function to return the instance but this is much nicer)
public static C_Player Instance { get; private set; }

//Assign the instance as soon as the script starts
void Awake()
{
        Instance = this;
}

So from then on you could gain access to the object by just calling “C_Player.Instance”

This implementation would vary slightly if you’re not using a MonoBehaviour, you could set it up like this:

private static C_Player m_Instance;

public static C_Player GetInstance()
{
        if(m_Instance == null)
        {
               m_Instance = new C_Player();
        }

        return m_Instance;
}

This code will basically create the instance the first time it’s called, and subsequently every time it is called it will return the same instance unless it has somehow been destroyed.

Hey MADmarine,

Thanks so much! That was a perfect answer. I’ve got most of these object on gameobjects (and monobehaviours) for tweaking in the inspector etc. But the second snippet of code made what was happening in the first even clearer…

cheers