How to set up things up

Ok so I am getting stressed because I cant figure how to set up my scripts I had like 12 scripts all working but things didnt need to be so stretched out so I decided to condense everything and optimize as much as I can. But I want a game Manager script, here is what I need my game manager to do(What it currently does)

Set Up the Enemies
Control the Game State

It needs to work with the enemy AI script and the Player scripts

The EnemyAI script handles the enemy movement the enemy attack and the power up drops

The Player Script handles the player health, player points, the player movement and the players attack,

I had set up the EnemyAI and Player Scripts to inherit from GameMaster and it worked fine… everything was peachy but recently People have said it wasnt smart according to standards I knew that but I did it anyway. Now I’d like to follow the standards. But I cannot get these scripts to work together without either making the 2 scripts inherit from GameMaster or making my variables static… both of these methods are nog good practice and using Get Component doesnt give me errors but when the game starts for some reason the variable returns null even when I set it up in the start method and when I drag the GameManager gameObject onto the public variable slot on my player and enemy AI GameObjects everything works. Here the part my scripts that matter

The variable at the top of the script

public GameManager gameManager;

The part in start where I assign GameManager

gameManager = GetComponent("GameManager") as GameManager;

How I’ve used the variable gameManager throughout the script

gameManager.enemyCount

So why is is returning null when the game is ran… I’d love to know the best way to use variables across scripts…

Hello there!

GetComponent only looks for a component which is attatched to the same gameobject as the script using the function.

You could use the GameObject.Find function to find an object with a specific name and then use GetComponent on the found object. But honestly I’d recommend a singelton solution. This piece of code goes in the GameManager script:

public static GameManager Instance;

void Awake()
{
    Instance = this;
}

Now any script can access the GameManager in your scene by using the Instance:

GameManager.Instance.enemyCount

Just make sure there is exactly one GameManager in your scene and everything should be fine.

Thanks you so much I never used singletons before but this worked flawlessly thanks again… I now know how to do this for the future too