How can I handle scripts correctly? What's a good way to apply scripts to GameObjects?
Hi all. I'm new to Unity. In the past 6 days, I've been reading guides, browsing the manual and watching video-guides.
I'm making a simple 2d game in Unity for school which consists of 4 mini-games. On my first mini-game, the objective is to move a character on a 2d field with the accelerometer and to pick objects in a limited timespan. A very simple game. However, there's only one thing that puzzles me: where do I apply the scripts?
They are easy to write, that's true. But what's the best way to apply them to a gameobject?
If i make a script that destroys the collectible when the player touches it and instantiates a new one in a random position, i could place this script on the player GameObject, but then if i want to do "score++" each time player touches a collectible i should keep track of the score in the player script. If i wanted the timer to reset everytime player touches an object, i should keep track of time in the player script, and so also the GameOver() function should be put in the player script. I just attached the script that handles the entire mini-game on the player object.
What if i want the playerScript to call a function from another script (and from another object)? For example:
void OnTriggerEnter2D(Collider2D trigger)
{
if (trigger.tag == "Enemy")
{
MiniGameManager.GameOver();
}
}
There could be hundreds of ways to bring the game to a "Game Over", but i can't always repeat the same code. A good way for me would be to make a mini-game manager that is visible to all the scritps in the scene. How can i put this in practice, without draggin and droppin the "mini-game manager" everywhere?
Thank you in advance for your availability.
Answer by Kishotta · Feb 06, 2018 at 07:09 PM
I'd highly recommend you use a Singleton for your game manager. As the name implies, you can only ever create a single instance of a singleton. You should be able to access it from anywhere in your code with something like:
MiniGameManager.Instance.GameOver();
The OP should notice that not all scripts need to be $$anonymous$$onoBehaviours and instantitated on GameObjects. You can have your game manager singleton anywhere. Of course it may be convenient to make the game manager a game object, if it needs to interface with Unity engine i.e. respond to Start, Update, OnApplicationQuit and other such callbacks.