Trying to optimize my code for resource gathering

Nothing big, just looking for a more logical way to put my code together. I have 3 resources in my game, trees, rocks, and fish. I want to have it where when a player walks up to a resource I can use 1 function that sends the appropriate “damage” to the node.

I am working on a multiplayer game, so there’s a little extra code I have to put in.

This is what I have so far. The code all works, but it feels like I could be doing it more efficiently:

void CmdGatherResource (NetworkInstanceId netId)
{
   GameObject focus = NetworkServer.FindLocalObject (netId);

   GatherTree resourceTree = focus.GetComponent<GatherTree>();
   GatherRock resourceRock = focus.GetComponent<GatherRock>();
   GatherFish resourceFish = focus.GetComponent<GatherFish>();
   if (focus)
   {
      PlayerStats playerStats = GetComponent <PlayerStats>();
      if (resourceTree != null)
      {
         resourceTree.Gather (playerStats.woodCutDmg);
      }
      if (resourceRock != null)
      {
         resourceRock.Gather (playerStats.rockMineDmg);
      }
      if (resourceFish != null)
      {
         resourceFish.Gather (playerStats.fishCatchDmg);
      }
   }
}

Basically I just want to know if after I set the GameObject focus if I can check what type of resource it is. Is there a way to set a bool or string on the resource code that I can check for? If the bool or string is set to 1 of the 3 resource types, then I can use the specific code necessary. I realize I could use tags, but the tag is already used for other code so I need an alternative.

You could make a parent class “Gather”, use GetComponent to get that, and then check which of the three subclasses it is. Or, similarly, you could make some sort of info class and use that to store what type of Gather component is attached to the object.

In general though, other than tags, you’re not going to find an easy way to directly store values on an object outside of a component.

I’ll try that, I actually already have a base class that I derive from so maybe I’ll expand on that. Thanks for the suggestion!

I kinda figured it would be a long shot but I had to ask and see if anyone knew a way. I mean it works regardless, so its not a major issue

Use an interface or a common component for all resource gathering. Then deal with that. Unless there is a fundamental difference between the nature of the different resources, there is no reason why they all can’t use the same component.

I’ll look into interfaces, I’m not familiar with them. Basically the only differences I have is perhaps the “health” of the resource node, what skill is being used to harvest the node, and what/how many items are given to the player when the resource node is harvested

All of these can be configured via variables. I think one type will suit your needs.