GetComponent By inheritance type issue.

Hi,

Im struggling a bit with GetComponent. Im making a spells system, and the playerPrefab has four public variables which are GameObjects. Each of those gameobjects will have 1 script component attached which is a class which must extend ‘Ability’. So therefor i do not know the calss type for the script, but i know the inherited type.

How can i access those scripts?

using UnityEngine;
using System.Collections;

public class CombatSystem : MonoBehaviour
{
	public Transform target;
	public GameObject ability1;
	
	void Start()
	{
                // this doesnt work. i seem to only be able to access the parent variables (Ability)
                Ability ab1 = ability.GetComponent<Ability>();
                ab1.damage = 10f;

                // this works.. but i shouldnt know its of type Volley.
		Volley ab1 = ability1.GetComponent<Volley>();
		ab1.damage = 10f;
	}
	
	void LevelUp()
	{
          ...
	}
	
	int CalculateAttackDamage()
	{
          ...
	}
	
	void Update()
	{
          ...
	}
	
	
}


using UnityEngine;
using System.Collections;

public class Volley : Ability
{
	public float damage = 1f;
}

Yes GetComponent< Ability >() does retrieve the object, but it only knows about the variables that are part of Ability because that is the common set you have requested. I guess the variables and methods you are accessing should be in the parent or you should use interfaces to declare and implement behaviours.

try:

   public class Volley : Ability
    {  
     public float damage = 1f;

     void Start()
     {
       spellType = this;
     }  
   }

Modify your Ability with this variable:

public class Ability : MonoBehaviour
{
   public Ability spellType;
}

then use :

Ability ab1 = ability1.GetComponent<Ability>().spellType;

untested , but should work.