Programming 101 Question

Ok. I’m working on a resource system. Every resource type shares the same variables. They also all have a function to handle consumption of the resource per cycle. Let’s call it Consume(). However, the computation for the consumption (the body of Consume()) is different for each type of resource.

Now, my question is, what’s the best approach to coding that? My only thought is to create a resource class with the variables and a virtual Consume() function, and then have each resource type inherit from that class, redefining Consume() for each. That way, I can iterate through an array of all resources and each calls its own Consume() function. Is that the best approach?

I’m just a novice myself, so this may not be the best way. Why not use a switch statement inside a single Consume() function that checks the resource type and executes based on that?

for example:

// pass whatever you are using to identify resource, string, whatever

function Consume(resource : String) 
{
 switch (resource)
 {
   case "a":
    //do computation for resource a
    break;

   case "b":
    //do computation for resource b
    break;
  
 }

}

Jason

Yeah. I hadn’t considered that. That would probably save me a lot of trouble.

The OP’s solution is much more flexible than using a switch, and is a more generally accepted OO solution to the problem. Something like

class Resource {
	virtual function Consume() {
		Debug.Log("Consume1");	
	}
}

class Resource2 extends Resource {
	function Consume() {
		super.Consume();
		Debug.Log("Consume2");
	}
}

function Awake () {
    	var resource2 : Resource = new Resource2();
	resource2.Consume();
}

works perfectly well.

If you’re uncomfortable extending classes and using virtual functions (for which there aren’t a lot of Unity Javascript / Unityscript-specific tutorials), Unity provides for you the SendMessage() and BroadcastMessage() methods. Using these methods is more expensive than using abstract classes or interfaces (the latter of which is not supported AFAIK in Unity’s flavor of Javascript), but gives you even more flexibility, as the receiver of said message can ignore the request entirely if you use the SendMessageOptions.DontRequireReceiver parameter in send/broadcast message.

Why, yes it does. Ok, then. I’ll stick with the original design. Just didn’t know if it was the best approach.