I have 100 gameObjects,If player goes inside them , they should give player score or other stuff.
I can create an OnTriggerEnter2D function inside every 100 gameobjcets .so when another Collider2D enters them , they give it score, Or I can create just an OntriggerEnter2D function in my playerController with 100 ifs to tell him if other.tag==“object 1”, gives 10 scores,or if (other.tag==“object 2”) gives 40 scores and …
Hope you guys get what I want.
I would create OnTriggerEnter2D function in the playerController and instead of having so many if conditions give all of them a common tag say “scoreObject”. Also add a script to each of these objects say “AddScore” and this script has an int that describes the amount of score they give. Now you can do something like this:
public class AddScore : MonoBehavior {
public int scoreAmount = 10; // Change this value for each object in the inspector
}
public class PlayerController : MonoBehavior {
int totalScore;
void OnTriggerEnter2D(Collider other) {
// check if its the score object
if (other.tag == "scoreObject") {
// Get the AddScore component attached on this object
AddScore component = other.GetComponent<AddScore>();
// Add the score amount to total score
totalScore += component.scoreAmount;
}
}
}
So basically instead of doing multiple if’s, just read the different score amounts from the component attached to these objects.
That tagging system seems like a dreadful idea give each its own script with a public int score. Then when it collides, get the component and the score and simply add it. Don’t try to over-engineer something so trivial. Keep it nice and simple.
EDIT:
And stop trying to optimise such trivial things. An if statement has almost 0 impact on performance so stop thinking like that.