Unity问题中的继承

时间:2016-05-11 03:09:16

标签: c# unity3d

我正努力让我的所有能力都遵循超类中的指令来减少重复代码的数量。我尝试通过传递Monobehavior作为构造函数中的参数来做到这一点。这将完美地工作,除了我收到警告说我根本不能这样做。这是我的超级班。

    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);

}

这里是其中一个子类,它可以很好地工作。

    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();

}

}

这是非传统的,但应该有效。无论如何在没有通过Monobehavior的情况下完成同样的事情。我不能扩展多个类,我需要它来扩展MonoBehavior。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您可以访问基类继承成员到派生类。为了澄清,假设您有ExtendMonobhevior类(您自己的Monobehaviour版本以及其他功能)。

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

现在你可以从MonoBehaviourExtended(你的MonoBehaviour的自定义扩展版本)驱动正常的类(你想用gameobjects附加),它还包含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

}

您也可以完全访问MonoBehaviour。