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 e.g. main_player and computer_player to inherit from a single class player with its own defined functions e.g. move()?
2 Answers
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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
Comments
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
5 Comments
base. simply don't write anything and let the normal inheritance work.computer_player and main_player are in two separate scripts how would they inherit from the same abstract class Player.
public abstract class Playeras the base class,public class MainPlayer : Player, andpublic class ComputerPlayer : Player?playerto apply to both human players and so characters.