- Home /
Is there an elegant way to having single-player class methods within a multiplayer class?
Hey!
I am making a game with both single-player and multiplayer features (I am using Unity Networking, for this). The scripts are identical with the exception to the LocalClient checks, RPCs etc in the networking scripts.
Here's a single-player script: using UnityEngine;
public class Shoot : MonoBehaviour
{
// variables
void Start ()
{
// assigning Get.Components to references here
}
void Update ()
{
Aim();
Shoot();
}
void Aim ()
{
// Aiming code here
}
void Shoot()
{
// Shooting code here.
}
}
At the moment I have copied pasted the code from the single player to the multiplayer. For example,
{
void Update ()
{
if (!LocalPlayer)
{
return;
}
Aim ();
Shoot ();
}
void Aim ()
{
// Aiming code here
}
void Shoot()
{
// Shooting code here.
}
}
It works; but it feels inelegant. Normally I would use inheritance but I cannot because the class must derive from NetworkBehaviour, otherwise I will not be able to do RPC and LocalPlayer checks.
So what would you do? Would you have approached the code architecture in a different way?
if (!isLocalPlayer)
{
return;
}
using the above code is right.Refer Unity learn section https://unity3d.com/learn/tutorials/topics/multiplayer-networking/identifying-local-player
Answer by tomtominc · Apr 08, 2016 at 06:58 AM
This is totally fine, maybe try this?
if ( !LocalPlayer ) return;
enter code hereYou could also do something like this if you REALLY want to use inheritance.
public abstract class NetworkPlayer : NetworkBehaviour
{
protected abstract void Aim();
protected abstract void Shoot();
}
public class ClientPlayer : NetworkPlayer
{
protected override void Aim()
{
// client aim stuff
}
protected override void Shoot()
{
// client shoot stuff
}
}
public class OnlinePlayer : NetworkPlayer
{
protected override void Aim()
{
// online aim stuff
}
protected override void Shoot()
{
// online shoot stuff
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612074319im_/https://answers.unity.com/themes/thub/images/avi.jpg)