- Home /
How to create a score manager script involving awarding points from multiple objects?
I have many objects which award the user points dependent on which object has been tapped. So I thought of creating an enum for these objects, as they are of the same type and tried to use a switch statement to make it more efficient.
However, the problem is that I have created a script for each object where the scripts for these objects are nearly identical except for the line of code which awards the user points within the onmousedown() method for when the user taps an object, and I don't know how to put this all into one script to reduce clutter in my game. I'm not very good at coding which is why I'm having this trouble.
Also, the score is calculated within my main game controller script, so I'm calling the method which calculates the score in the scripts attached to each object to output the overall score.
Can someone show me how to efficiently do this? As I don't want to constantly add a new script to every new object I make.
Answer by myzzie · Sep 09, 2018 at 05:57 PM
Without knowing what "difference" you want between the gameobjects, this is how you can add different values depending on which gameobject this script is attached to.
public int scoreToGive;
void OnMouseDown()
{
Scoremanager.AddScore(scoreToGive);
}
Hi, thanks for the response. Sorry for being vague, but I've figured it out now.
Answer by tormentoarmagedoom · Sep 09, 2018 at 06:05 PM
Good day.
As you also have a game controller script, the best way is:
In all objects. have exactly the same script, that the only thing that do is to call a funciton in the game controller script, with a parameter, so the method can know what object called it. This parameter can be the name of the object, or the tag of the object, or something for "classify" all objects that can be cliked. you will have 1 script with only 1 function controlling, everything.
For example, at the game controller do this:
int TotalPoints;
public void ObjectHasBeenClicked(string objectTag)
{
int pointsToAdd
switch (objectTag)
{
case "Coin":
pointsToAdd = 2;
//Something
break;
case "Ring":
pointsToAdd = 2;
//Something
break;
case "Diamond":
pointsToAdd = 2;
//Something
break;
}
TotalPoints += pointsToAdd;
}
So every time a object is clicked you need to call this method from the objectsScript giving the tag name of the object clicked.
GameControllerScript.ObjectHasBeenClicked(gameobject.tag);
Bye!
Hi, thank you!! This was what I originally thought of and implemented, but it didn't work properly. I ended up putting all the if statements within the onmousedown() method which worked fine.