Pookie
Pookie

Reputation: 1279

Inheritance in Unity issue

I am trying to get all my abilities to follow instructions from a superclass to decrease the amount of repetitive code. I tried doing this by passing in Monobehavior as a parameter in constructor. This would work perfectly, except I get a warning saying I simply can't do this. Here is my super class.

    public class Ability : MonoBehaviour {


private SpriteRenderer renderer;
private MonoBehaviour ability;
public Ability(MonoBehaviour b) {
    ability = b;
    renderer = ability.GetComponent<SpriteRenderer>();

}

public void Start () {

}


void Update () {

}

public void checkAvailability()
{

    if (ability.GetComponentInParent<SpeedBall>().getAvail())
    {
        renderer.enabled = true;
    }
    else
        renderer.enabled = false;
}

public void updateRenderer()
{

    renderer.enabled = true;
    renderer.transform.position = ability.GetComponentInParent<BoxCollider>().transform.position;

    renderer.transform.localScale = new Vector3(.2f, .2f, 0);

}

and here is one of the child classes, which would work perfectly.

    public class Sprite : MonoBehaviour {

private Ability ability;
void Start () {

    ability = new Ability(this);
}

// Update is called once per frame
void Update () {
    ability.updateRenderer();


    ability.checkAvailability();

}

}

This is untraditional, but it should work. Is there anyway to accomplish this same thing without passing in Monobehavior. I can't extend multiple classes, and I need it to extend MonoBehavior. Thanks for any help!

Upvotes: 0

Views: 145

Answers (1)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10561

You can access base class inherit members into derived class. For clarification suppose you have ExtendMonobhevior class (Your own version of Monobehaviour with additional functionalities).

class MonoBehaviourExtended : MonoBehaviour { 
    //your extended featuer of MonoBehaviour goes here
}

Now you can drive your normal classes(which you want to attach with gameobjects) from MonoBehaviourExtended(your custom extended version of MonoBehaviour ) it also contains MonoBehaviour

//inherit with extended monobehviour also contains extended features
public class Player : MonoBehaviourExtended { 
    //your normal class functinality
}

//inherit with extended monobehviour also contains extended features
public class Enemy : MonoBehaviourExtended
{
    //your normal class functinality

}

And you get full access to the MonoBehaviour also.

Upvotes: 1

Related Questions