Reputation: 2771
I have some things to clarify for myself, so please bear with me.
Let's say I want to have an object that will explode after a certain period of time. If the object explodes while the person is still holding it, you get killed.
Let's consider the following implementation:
public interface IKillable
{
void Kill();
}
public interface IExplodable : IKillable
{
float TimeLeft { get; set; }
void Timer(float timeToExplode);
}
public abstract class Bomb: IExplodable
{
public float TimeLeft { get; set; }
public void Kill()
{
//Destroy the object
}
public void Timer(float timeLeft)
{
if (TimeLeft <= 0) {
Kill();
}
}
}
What if I also want to add let's say a "Backpack" instead of "Bomb" that will have the exact same functionality or any other item that can explode (and kill)?
Upvotes: 0
Views: 182
Reputation: 32068
Having a base class that provides common functionality for objects is both common and recommended in Unity.
Instead of calling the class Bomb
, call it something more generic, like ExplodableDevice
(as @zmbq answered). I would, however, make it more explicit that the device explods due to a timer, so perhaps TimerExplodableDevice
. Notice that the base class should inherit from MonoBehaviour
as otherwise you wouldn't be able to use those objects fully (as c# doesn't allow multiple inheritance).
An example of such implementation would be:
public interface IKillable
{
void Kill();
}
public interface IExplodable : IKillable
{
float TimeLeft { get; set; }
void Timer(float timeToExplode);
}
public abstract class TimerExplodableDevice: MonoBehaviour, IExplodable
{
public float TimeLeft { get; set; }
public virtual void Kill()
{
//Destroy the object
}
public virtual void Timer(float timeLeft)
{
if (TimeLeft <= 0)
{
Kill();
}
}
}
// this should be in a "Devices" folder, or otherwise be called appropriately
public class Backpack : TimerExplodableDevice
{
void Start()
{
TimeLeft = 100;
}
}
// this should be in a "Devices" folder, or otherwise be called appropriately
public class Bomb : TimerExplodableDevice
{
void Start()
{
TimeLeft = 10;
}
}
Upvotes: 1
Reputation: 39013
You can create an abstract ExplodableDevice
class and have Bomb
and Backpack
inherit from it.
Upvotes: 1