Hello, I’m currently making multiplay shooting game using unity net code.
current version is unity 2022.3.20f1, and net code 1.8.1.
what I did is
- create empty object called Network Manager and attach Network Manager and Unity Transport component.
- assign player prefab, and create network prefabs list which has player prefab and bullet prefab, and assign it into network manager component.
- In player prefab and bullet prefab, add Network Object and Network Transform component.
- create empty object Called Shooting Manager and add Network Object and Shooting Controller Script.
this is Shooting Controller script.
using UnityEngine;
using Unity.Netcode;
public class ShootingController : NetworkBehaviour
{
public GameObject bulletPrefab; // Assign your bullet prefab in the Inspector
void Update()
{
// Detect user input (left click or touch)
// Ensure the input is processed only if this is the owner's client
if (IsClient && IsOwner && Input.GetMouseButtonDown(0))
{
ShootBulletServerRpc(NetworkManager.Singleton.LocalClientId);
}
}
[ServerRpc(RequireOwnership = true)]
private void ShootBulletServerRpc(ulong clientId)
{
// Instantiate the bullet at the camera's position and rotation
GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
NetworkObject networkObject = bullet.GetComponent<NetworkObject>();
if (networkObject != null)
{
networkObject.Spawn(); // Spawn the bullet over the network
// Initialize the bullet's properties, such as setting its owner
BulletController bulletController = bullet.GetComponent<BulletController>();
if (bulletController != null)
{
bulletController.SetOwner(clientId);
}
}
}
}
and then, I assigned bullet prefab in the Shooting Manager.
After that, I build it for linux dedicated server , and upload the build to the server and run.
it’s kinda working, but I’m having null reference error in GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation); even though prefab has been assigned.
so I put log and found, after connecting to the server, suddenly bulletPrefab becomes null.
I do not have any clue why this is happening.