using addcomponent for buffs, using variable for class

I’m trying to build a tiny turn-based battle engine and I hit a roadblock adding ‘buffs’ to my characters. I have the buffs as children of a parent class called ‘Status’ and am trying to add them to my Character class as components. I had it working just fine once, but I tried to make the function adding the component more generic and now get the error

no appropriate version of ‘unityEngine.GameObject.AddComponent’ for the argument list (Status) was found

Adding the buff component - contained in and called by my parent skill class:

function addStatus(user: Character, buff: Status){
	var nStatus = user.gameObject.AddComponent(buff);
}

this is how I am calling the addStatus, inside a child skill ‘shield’:

	var buff: shielded;
	super.addStatus(user, buff); 

shielded is a child of the Status class. All of these classes are contained in different .js files.

This same code works when I put a specific ‘buff’ into the call = addComponent(shielded); So I assume I’m just using the function wrong or I have completely misjudged how to go about this problem.

If you need to know anything more specific to see what is going wrong, please let me know. Thank you,

The syntax you're using suggests that buff is an object reference. AddComponent doesn't want an object, though, it wants a type. You can ask an object what its type is, for example buff.GetType(), but I don't have a Unity install handy to see how well that works with AddComponent. Do you really need buffs to be components? Depending on what you need them to do, it might be easier to work with if they're objects that are managed by a component (like a "BuffManager", say).

A buff manager could be a good idea, but certain temporary effects might as well manage themselves too. In a turn-based game I don't think that would be too much work for the system.

1 Answer

1

You might better off making the argument to AddComponent() a string or using typeof(class). You could make an enum named Statuses and make it the second argument to addStatus(). Pseudocode:

enum Statuses
{
	Shielded,
	Regeneration
}
	…

function AddStatus(user : Character, type : Statuses)
{
	switch(type)
	{
	case Statuses.Shielded:
	user.AddComponent(Shielded);
		…
	}
}

If all the components are added directly to the character, the variable gameObject already refers to it. So you shouldn’t really need the “user” and “super” variables either. It could then be simplified just to AddStatus(type : Statuses).

I'll mess around with this idea. The idea of the character and why I wanted things to be so generic was to allow for different attacks to add and remove buffs. So a character can use a skill that adds a shield to themselves but also adds a 'debuff' to their enemy as part of the same turn. I appreciate the answer. Combining this with the comment above of a 'buff manager' might end up being the way I go.