- Home /
Duplicate Question
The best way to create instances of an enemy class
I have studied object oriented programming and unity in general for a while now. However I'm still not sure how to accomplish the following:
Say I make a base character class that contains all the attributes shared by both players and enemies (strength, dex, intelligence etc.) and I want to create unique instances of this class and attach those instances to game objects. These instances could in turn be used by other scripts that control combat etc. It's vital that the instances have differing values on the attributes contained in the base character class. What is the best way to create instances like that?
I couldn't work out how to do this so I just made two separate scripts that basically did exactly the same thing and attached those scripts to the player and enemy game objects. Very bad coding practice, I know, but I'm not sure how to use inheritance etc. as surely the script would have to inherit from monobehaviour if I am going to attach it to an object?
Answer by Limbo · Oct 07, 2014 at 05:04 AM
I think you just want to be inheriting like so C#
public class BaseClass : MonoBehaviour
{
public int health;
}
so that's the class the both the player and enemy can/will share, let's say now you want to create the player script
public class Player : BaseClass
{
void Start()
{
Debug.Log("Health: " + health);
}
}
now your player has health because BaseClass has it too
so you attach the baseClass to the player and enemy game object? And then you create separate classes that inherit from baseClass for every instance of the class that you want? How do you attach those specific instances to game objects or do you need to?
Seems like the link you need is not the one @Landern provided but more this one http://msdn.microsoft.com/en-us/library/vstudio/ms173149(v=vs.100).aspx
ah man! I finally understand. $$anonymous$$y problem was that I got it stuck in my head that in order for a class to be attached to a gameobject it needed to inherit directly from monobehaviour. But if it inherits from a class that inherits from monobehaviour, then it inherits from monobehaivour!!!! Ah dude. That took me a long time to work out. haha.
Yes, you only attached Player.cs to you gameObject and your component will be something like this Player<-BaseClass<-$$anonymous$$onoBehaviour so you are really attaching a script component that in it's lowest level is a $$anonymous$$onoBehaviour... well $$anonymous$$onoBehaviour also Inherited from Object... but yeah you got it right.
Answer by Landern · Oct 07, 2014 at 04:44 AM
@bunny83 addressed this a while ago, please read: http://answers.unity3d.com/questions/119516/inheriting-from-a-class-that-inherits-from-monobeh.html