If Statements with FindGameObjectWithTag

Hello!

I can’t seem to figure out how to put this into If/Else

GameObject.FindGameObjectsWithTag("Stone");
gameObject.GetComponent<Rigidbody2D>().mass = MassDB.Stone_Mass;

That’s working fine to find the child of an object with the tag stone, and set the mass accordingly.

I need to be able to have it check for other tags too.

Kinda like this but, you know…more codey :smiley:

if		
GameObject.FindGameObjectsWithTag("Stone");

gameObject.GetComponent<Rigidbody2D>().mass = MassDB.Stone_Mass;
		
otherwise

if
GameObject.FindGameObjectsWithTag("Copper");
gameObject.GetComponent<Rigidbody2D>().mass = MassDB.Copper_Mass;

Thanks a lot!

Are you placing this script on one general GameObject that sets the mass of all the GameObjects in the scene, or are the GameObjects setting their own masses based on their tags?

For the first way (if you have one “manager” GameObject that is setting all the masses for tagged objects in its Start() or something), you’re probably really looking for a foreach statement. GameObject.FindGameObjectsWithTag("Stone") returns a collection of GameObjects, and you’re not actually using it in your code above. Something like:

foreach(GameObject g in GameObject.FindGameObjectsWithTag("Stone")) {
    g.GetComponent<Rigidbody2D>().mass = MassDB.Stone_Mass;
}
foreach(GameObject g in GameObject.FindGameObjectsWithTag("Copper")) {
    g.GetComponent<Rigidbody2d>().mass = MassDB.Copper_Mass;
}
// etc..

If it’s the latter situation (each Stone or Copper object is using the script to set their own mass), you don’t need to search the whole scene. Just check the tag of the GameObject and set the mass accordingly:

if (gameObject.tag == "Stone") {
    gameObject.GetComponent<Rigidbody2D>().mass = MassDB.Stone_Mass;
}
else if (gameObject.tag == "Copper") {
    gameObject.GetComponent<Rigidbody2D>().mass = MassDB.Copper_Mass;
}

rombaaaaaaa thanksss