How to inherit from a class that inherits from MonoBehaviour
Im trying to implement a base class such as this:
public class Entity : MonoBehaviour
{
public float speed = 0.05f;
public float maxHP = 100f;
protected float currentHP = 0;
public float GetMaxHP()
{
return this.maxHP;
}
public float GetCurrentHP()
{
return this.currentHP;
}
public float GetSpeed()
{
return this.speed;
}
public void DamageHP(float damage)
{
this.currentHP -= damage;
}
}
and inherit it from this class:
public class PlayerBehavior : Entity
{
void Start()
{
}
void Update()
{
}
}
and when I try to drag the PlayerBehaviour script to the player, an error pops out:
Can't add script behaviour AssemblyInfo.cs. The script needs to derive from MonoBehaviour!
your code is fine, can you try creating 2 new scripts and check if the error persists? in case is some error with class overriding or something like that, you are attaching the playerbehaviour cs to the gameobject rigth?
@xxmariofer yes Im attaching it to the gameobject, when I attach the entity class it works but not the player
Can ylu try access the methods fron the ñarent class? Gives you errors?
I'm having the same problem. I think the issue is that Unity is failing to recognize that the class is a subclass of $$anonymous$$onoBehavior because for some reason the linkage was never generated. I've also noticed that VisualStudio is being terrible and it's not recognizing any classes in any of the other files, but once saved everything compiled through Unity fine. I don't recall Visual Studio being this bad when I used it in the past for projects unrelated to Unity, so I think the problem might be related to that.
Answer by Zimogor · Nov 15, 2020 at 06:44 PM
World "Entity" is reserved by Unity for so called "Entity Component System". So when you inherit from Entity, you inherit not from your Entity, but from ECS Entity. Rename you class name, your resolve name collision somehow.