Question by
Topsu · Nov 09, 2017 at 09:53 PM ·
networkingmultiplayer-networkingobject-oriented-programming
Networking attributes through interface
Hello, I have my WeaponControl script call functions in my weapons through IWeapon interface, but the problem is that I cannot use NetworkServer.Spawn(bullet); on my weapon, even with the [Command] attribute because I get error "NetworkServer is not active. Cannot spawn objects without an active server."
Everything works fine on host side though.
WeaponControl.cs
public class WeaponControl : NetworkBehaviour {
// Use this for initialization
private IWeapon currentWeapon;
void Start () {
}
// Update is called once per frame
void Update () {
if (!isLocalPlayer)
{
return;
}
if (CrossPlatformInputManager.GetButtonDown("Fire1" + tag))
{
currentWeapon.CmdCharge();
}
if (CrossPlatformInputManager.GetButtonUp("Fire1" + tag))
{
currentWeapon.CmdFire();
}
}
public void Switched(IWeapon newWeapon)
{
Debug.Log("New Weapon");
currentWeapon = newWeapon;
}
}
IWeapon.cs
public interface IWeapon
{
void CmdFire();
void CmdCharge();
}
Gun.cs
public class GunController : NetworkBehaviour, IWeapon
{
public GameObject bulletPrefab;
public Transform bulletSpawn;
public double timeToMaxCharge;
public float minCharge;
public float maxCharge;
public double cdAmount;
private double timeStamp = 0; //cooldown
private double chargeStart;
private float charge;
private bool onCd;
public int parentIdShow;
[SyncVar(hook = "CallbackSetOwner")]
public NetworkInstanceId parentId;
private WeaponControl weaponControl;
// Use this for initialization
void Start () {
weaponControl = gameObject.transform.parent.gameObject.GetComponent<WeaponControl>();
weaponControl.Switched(this);
//gameObject.transform.position = gameObject.transform.parent.Find("GunPosition").transform.position;
}
[Command]
public void CmdCharge()
{
if (timeStamp <= Time.time)
{
onCd = false;
}
chargeStart = Time.time;
}
[Command]
public void CmdFire()
{
if (!onCd)
{
double chargeTime = Time.time - chargeStart;
double chargePercent = chargeTime / timeToMaxCharge * 100;
charge = (float)maxCharge / 100 * (float)chargePercent;
if (charge > maxCharge)
{
charge = maxCharge;
}
if (charge < minCharge)
{
charge = minCharge;
}
Debug.Log(charge);
// Create the Bullet from the Bullet Prefab
var bullet = (GameObject)Instantiate(
bulletPrefab,
bulletSpawn.position,
bulletSpawn.rotation, gameObject.transform);
// Add velocity to the bullet
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * charge;
timeStamp = Time.time + cdAmount;
NetworkServer.Spawn(bullet);
}
onCd = true;
}
}
...
Comment