How to add and sort a list of gameobjects by tag?

I’m relatively new to using lists/programming in general, and I’m having difficulty with the following script:

public List<GameObject> planetList = new List<GameObject>();

void Update ()
{	
	if (Physics.Raycast(ray, out hit)) 
	{
		planet = hit.collider.gameObject;
		
		if (planetList.Contains(planet) == false)
		{
			planetList.Add(planet);
		}
	}
}

This is working fine, however each planet is being added to the list as their game object name (“Planet”) I’d like to add and name each planet to the list according to their tag, for example:

if (Physics.Raycast(ray, out hit)) 
{ 
	planet = hit.collider.gameObject;
	
	if (planetList.Contains(planet) == false) 
	{
		if (planet.tag == "Earth")
		{
			planetList.Add(planet ("Earth", 1));
		}
	}
}

I also want to sort the list by each planet’s value e.g. Earth = 1, Mars = 2. Problem is, this returns the error “cannot be used as method or delegate”.

Why don’t use the tag value to sort your list ? I don’t know what you would do but use a tag for only one object it’s not the best way to use tag. ( At least for me, I prefer Enums ).
So just create an enum for all your planets and sort your list with your enum values.

    if ( !planetList.Contains(planet) ) 
       if ( planet.tag.Equals( "Earth" ) )
          planetList.Add(planet ("Earth", 1)); //What would you do here ?!

You can add all your planet then when it must be over then re-sort your list based on the tag array order (or Enum order) by swapping them or by any other methods.

Just call sort with a custom Comparison-function

int CompareByTag(GameObject O1, GameObject O2)
{
    return O1.tag.CompareTo(O2.tag);
}

planetList.Sort(CompareByTag);

Btw, why don’t you name your planets with their actual name? That’s the purpose of a name, to distinguish similar things, like humans…

if you have a GameObject you can simply set the name, well, by setting it’s name property:

planet.name = "Betelgeuse";

If you want to sort by name, just create another Comparison function and compate the names instead.

ps: The purpose of a tag is actually to “mark” / “group” similar objects. So “Planet” would be a perfect candidate for a tag. A name on the other hand is ment to give something a unique name. It seems you use them in reverse…