简体   繁体   中英

Inheritance for multiple unity gameObjects C#

I am only new to unity and C# though I have an intermediate - advanced knowledge of python. I have learned the fundamental elements of C# and am currently trying to create a game of Pong using the Unity 2d platform. I am unsure if there is a clean and concise way for two gameObjects eg main_player and computer_player to inherit from a single class player with its own defined functions eg move() ?

You can Create a class player like this.

public class Player: MonoBehaviour {
    public virtual void move(){
    }
}

Then inherit it like this:

public class Computer_player:Player{
    public override void move(){
       base.move();
       //Extra movement code goes here    
    }
}

Same way you can inherit main_player. You can find more details here: https://unity3d.com/learn/tutorials/topics/scripting/inheritance

You can go with 2 methods, abstract or interface.

public interface IMove{
    void Move();
}

public class Main_player:MonoBehaviour, IMove{
     public void Move(){}
}
public class Computer_player:MonoBehaviour, IMove{
     public void Move(){}
}

You can use GetComponent on interface but you cannot use the slots in Inspector. interface are not serializable so you cannot make them appear in editor.

For this you need abstract.

public abstract class IMove : MonoBehaviour{
    public abstract void Move();
}

public sealed class Main_player: IMove{
     public override void Move(){}
}
public sealed class Computer_player: IMove{
     public override void Move(){}
}

Whether you make Move abstract or virtual is quite similar in result. If you have a default implementation, use virtual, if you require the subclass to implement its own version, then use abstract.

More here : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract

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