简体   繁体   中英

Inherits from a class that inherits networkBehviour

I'm trying to inherit a class that in NetworkBehaviour but whenever I inherit the parent class(script) stop working.

I have tried this:

using UnityEngine;  
using UnityEngine.Networking;   

public class FireFighter : NetworkBehaviour
{
    private void Update()
    {}
    private void Move()
    {}
    private void break()
    {}
} 

public class FireCaptain : FireFighter
{   
    public override void Move ()
    {
        base.Move();
        Debug.Log("The captainMoved.");     
    }
} 

In brief, FireFighter script works well but whenever I inherit it, it stops working. I need some help here. How can I inherit a class that inherits Networkbehaviour.

Be carefull with the naming of your methods! break is a keyword and should not be used as method name.


Then you defined

private void Move()

in your base class FireFighter

=> in FireCaptain you can not do

public override void Move ()
  1. because it is not virtual or abstract so you can't use override at all.
  2. even if it would be you can't change the scope (from private to public ) in an override.
  3. and since it is private in your subclass you don't even have access to call base.Move(); since it can be called only by the implementing class itself.

So

To 2.) & 3.) If you want it to be public in the subclass it also has to be public already in the base class. Or you can use protected so only the base class and its inheritors have access.

To 1.) To be able to override a method in your subclass it either has to be virtual or abstract . So make it

  • virtual if you want to have an implementation in the base class to define a default behaviour and make it only optional to override it Eg like

     // subclasses don't have to implement and override // this method but can. Also the base.Move(); is optional public virtual void Move() { Debug.Log("You might want to override this to implement a movement"); } 
  • abstract if you do not want to have an implementation in tha base class and want to force the subclasses to implement this eg like

     // subclasses will throw a compiler error if they // do not implement this method // (without base.Move(); since hte base has no implementation) public abstract void Move(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM