0

So I have these three classes for a game I'm making. Infection Controller, then 2 child classes, InfectedClass and BloaterClass. This is in the InfectionController:

void UpdateTarget()
{
    GameObject[] Humans = GameObject.FindGameObjectsWithTag(humanTag);
    GameObject[] Vaccines = GameObject.FindGameObjectsWithTag(vaccineTag);
    GameObject[] HV = Humans.Concat(Vaccines).ToArray();

    float shortestDistance = Mathf.Infinity;
    GameObject nearestHuman = null;
    Vector3 currentPosition = this.transform.position;

    foreach (GameObject huvacs in HV)
    {
        Vector3 directionToTarget = huvacs.transform.position - currentPosition;

        float distanceToTarget = directionToTarget.sqrMagnitude;
        if (distanceToTarget < shortestDistance)
        {
            shortestDistance = distanceToTarget;
            nearestHuman = huvacs;
        }
        else
        {
            targetHuman = null;
        }
    }

    if (nearestHuman != null && shortestDistance <= range)
    {
        targetHuman = nearestHuman.transform;
        infectionAgent.SetDestination(targetHuman.transform.position);
    }
}

So both the Infected and Bloater share this script but I want them to have different speeds. I ran into the issue where if I change the speed of the NavMeshAgent in my Start() function, I'm changing the speed of all the infection units to the same thing.

So... should I just put this movement method in the subclasses? Or is there a way to change the speed based on the subclass inside of the parent class?

1 Answers1

1

So... should I just put this movement method in the subclasses?

Is it going to be the exact same code? Then no. Never copy and paste the same code to multiple places.

If I change the speed of the NavMeshAgent in my Start() function, I'm changing the speed of all the infection units to the same thing [...] Is there a way to change the speed based on the subclass inside of the parent class?

You haven't shown your Start() method, but you should set the speed value from your sub-classes, not the parent class. Note that the Unity magic names (like Start) don't inherit well. You can create your own method (that's called from Start()) and is marked virtual allowing your subclasses to override it and get the behavior you want.