Abstract class with rigidbody?
Hi, I want to create an abstract class called Enemy, it contains values like HP, Speed, damage etc... can it have rigidbody also? because other enemies that will have this subclass will have a rigidbody aswell,
Comment
Answer by Vega4Life · Dec 11, 2018 at 11:06 PM
Of course. When you put your subclass on the gameObject, it will have the same inspector options as the base class (plus whatever you added to the subclass). Here is a quick example of two scripts - a base and a sub:
using UnityEngine;
/// <summary>
/// Base class for all enemies
/// </summary>
public abstract class BadGuy : MonoBehaviour
{
// Protected allows access from subclasses
[SerializeField] protected Rigidbody guyRigidBody; // Drag rigidbody to reference in inspector
[SerializeField] protected Collider guyCollider; // Drag collider to reference in inspector
[SerializeField] protected float startingHealth; // Preferably come from a scriptableObject
[SerializeField] protected float startingDamage; // Preferably come from a scriptableObject
[SerializeField] protected float startingSpeed; // Preferably come from a scriptableObject
public float Health { get; protected set; }
public float Damage { get; protected set; }
public float Speed { get; protected set; }
// Do awake things, but is virtual and can be overiden by a subclass
protected virtual void Awake()
{
Health = startingHealth;
Damage = startingDamage;
Speed = startingSpeed;
}
// An attack that can and probably should be overiden by a subclass
protected virtual void DoAttack()
{
// Does a basic attack
}
}
/// <summary>
/// Brusier class - has access to all public/protected member variabls and methods
/// </summary>
public class Bruiser : BadGuy
{
/// <summary>
/// We could override awake if we wanted
/// </summary>
protected override void Awake()
{
// If we still wanted to call the base for setting up our health, damage, speed, etc
base.Awake();
// We can do more awake things specific to this class
}
/// <summary>
/// Our bruiser attacks different than the base, so we override it
/// </summary>
protected override void DoAttack()
{
// Do a bruiser attack - doesn't use the base attack
}
}
Your answer
Follow this Question
Related Questions
Can not access an abstract class from another script! 0 Answers
My Enemies walk through objects and my FPS character model 3 Answers
Objects with triggers pass through each other 3 Answers
Rigid Body and Collision 1 Answer
Rigidbody - Stop & Jump 0 Answers