简体   繁体   English

多个unity gameObjects C#的继承

[英]Inheritance for multiple unity gameObjects C#

I am only new to unity and C# though I have an intermediate - advanced knowledge of python. 尽管我对python有一定的了解,但我对unity和C#还是陌生的。 I have learned the fundamental elements of C# and am currently trying to create a game of Pong using the Unity 2d platform. 我已经学习了C#的基本元素,并且目前正在尝试使用Unity 2d平台创建Pong游戏。 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() ? 我不确定两个游戏对象(例如main_playercomputer_player是否有一个简洁明了的方法从具有自己定义的功能(例如move()的单个类player继承?

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. 您可以继承main_player的相同方法。 You can find more details here: https://unity3d.com/learn/tutorials/topics/scripting/inheritance 您可以在此处找到更多详细信息: https : //unity3d.com/learn/tutorials/topics/scripting/inheritance

You can go with 2 methods, abstract or interface. 您可以使用2种方法(抽象或接口)。

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. 您可以在接口上使用GetComponent,但不能使用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. 无论您将Move抽象还是虚拟制作,结果都非常相似。 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 此处更多内容: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/abstract

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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