- Home /
C# code structure question
As an example, i have 2 classes, both doing almost the same stuff:
public class PlayerManager : MonoBehaviour
{
void Update()
{
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
Move(hit.point);
}
}
public void Move(Vector3 position)
{
// Move to given position
}
}
public class NpcManager : MonoBehaviour
{
void Update()
{
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
Move(hit.point);
}
}
public void Move(Vector3 position)
{
// Move to given position
}
}
Instead of detecting mouse click and finding hit.point in both classes Update, i'd like to move that code to a third class, which would then call the Move method of PlayerManager and NpcManager.
Of course i could require both scripts via GetComponent or other ways, but as my classes grow this becomes quickly unmantainable.
Any suggestions on how can i do this in a way that is mantainable even when expanding the codebase?
Your NPCs are going to be clicking the mouse? ;-)
Anyway, there's many options here. You might create a static class and start filling it with repeatable functions that other things are going to want.
This might be useful for you going forward as well. https://unity3d.com/learn/tutorials/topics/scripting/events?playlist=17117
You can use interitance. For example npc and player is both character so you can create a character class with these functionalities and that your player and npc will inherit from character class.
Another approach is creating a component that does this specific job and then you can add this component to your player and npc objects so that those classes can talk to that component to do the task.
It makes more sense to me to use inheritance for this case though.
I understand this approach. What i'm really asking is, having a Character generic class and Player / Npc classes inheriting from it, how do i use them in a third class which handles inputs?
Answer by JedBeryll · Dec 06, 2016 at 06:31 AM
For classes that are supposed to do mostly the same thing you should use inheritance. You make virtual methods so the inheriting classes can override if they need to do the same thing with a different code. It will keep your code manageable and fast.
https://msdn.microsoft.com/en-us/library/ms173149.aspx?f=255&MSPPError=-2147217396
http://answers.unity3d.com/questions/119516/inheriting-from-a-class-that-inherits-from-monobeh.html
Your answer
