Cant add a script as component. Type is derived by base class

Hej,

I’m working on a problem and yes i searched a bit.

My player is able to receive different ‘conditions’. A condition is a class derived from the base class Condition.

So for example the condution Stone derives from Condition.

Here is the code to add the condition:

using UnityEngine;
using System.Collections;

public class AddCondition : PlayerTrigger {

	// the condition we want to add
	public Condition c;
	// the players SpriteRenderer
	private SpriteRenderer playerSpriteRenderer;

	public override void Enter (GameObject _player, Rigidbody2D _playerRB)
	{
		// check if there are other conditions and remove them
		Destroy(_player.GetComponent<Condition>());
		// get the sprite renderer of the player
		playerSpriteRenderer = _player.GetComponent<SpriteRenderer> ();
		// play the change animation
		// TODO
		// change the sprite
		playerSpriteRenderer.sprite = c.image;
		// change the players mass
		_playerRB.mass = c.mass; 
		// add the condition itself
		_player.AddComponent<c>();
	}
}

but it says error CS0118: 'AddCondition.c' is a 'field' but a 'type' was expected

i tried c.name, c.GetType() and typeof(c).

The trigger is a gameObject which has the above script attached. And the field c is obviously the derived class I want to add to the players gameObject and is set in the inspector.

i believe i saw some code that does this but i cant find it anymore :frowning:

sidenote: i worked for many years as a Java and PHP / JS developer now so I habe to rethink a lot a my programing paradigms like this one. I think the compiler does now the type of component i want to add, its either condition or a derived class of it, And i dont know how to implement generics in this class since it derives itself from a class “PlayerTrigger” which checks if a collision is caused by the player and works as an interface with some overloaded methods and provides some variables for me, like the player object etc.

Thanks in advance :slight_smile:

If you want c to be a Class of Type Condition why do you not declare it like a class?

public Condition c = new Condition(); //(You class should have a constructor)

AddComponent is for adding MonoBehaviour derived scripts.

Well, as other have already said your “c” variable hold a Condition “instance” and AddComponent expects a “Type”. Components can’t be “moved” to other gameobjects or attached / detached after they have been created.

So if you just want to add a new instance of the same component as you have stored in your c variable, you just have to do this:

_player.AddComponent(c.GetType());

This will add the same class that the c variable is referencing to your player. The generic method only works with actual types at compile time. So you have to use the AddComponent variant that takes a System.Type object instead.