How to inherit properly

Hey guys,

So right now im having alot of trouble with figuring out something. So i have na abstract class called Spike, then i have 2 diferente spikes that inherit from the base Spike. On the base Spike i have an OnTriggerEnter2D event that gets the player’s componentes with “collision.GetComponent().etc…”. So up until here everything is fine. The problems comes in when i want one of the 2 spikes to access the players componentes. For exemple, one of the spikes inheriting from spike is supposed to lower the player’s speed but how do i access the player’s speed variable on that script if “collision.” does not work?

Thanks.

//This is my base Spike class.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Spike : Enemy 
{
    void Start()
    {
        dmg = 20;
        baseSpeed = 0;
    }

    protected new void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            Player t = collision.GetComponent<Player>();
            print("test");
            t.DropWalls();    //Drops created walls
            t.currentCount = 0;   //Sets our current wall count to 0
            SpikeEffect();
        }
    }
    protected abstract void SpikeEffect();

}


//This is the spike that is supposed to lower the player's speed


public class TimedSpike : Spike
 {

    float time = 5;
    
    protected override void SpikeEffect()
    {
        
        Destroy(gameObject, time);
        
    }

}

Ok, first of all you should never use the new keyword on methods. This will not properly override the method but just hides the original method. You should have declared the “OnTriggerEnter2D” as virtual in your Enemy class so you can override it in your Spike class.

Next thing is you do not pass on the collision information to your “SpikeEffect” method so the information is effectively lost. It depends on how versatile you want to design your classes but you may want to change the signature of your SpikeEffect method to something like this:

protected abstract void SpikeEffect(Player aPlayer);

So when calling the method you would do this:

SpikeEffect(t);

The derived class would look like this:

public class TimedSpike : Spike
{
    float time = 5;
    protected override void SpikeEffect(Player aPlayer)
    {
        // use aPlayer
    }
}

Your Alternative class also need an

 protected void OnTriggerEnter2D(Collider2D collision)
 {
       base.OnTriggerEnter2D(collision);

 }

to start, also an IEnumerator for time to hold a method before finishing could be handy. Would you want it to be protected though @bunny83?