hello, im trying to make some sort of a first person shooter game, i can spawn the player correctly with the isLocalPlayer bool set to true and all, but im not really sure how to spawn the gun, im using this code but its not working when a client connects
void Start()
{
hc = transform.parent.parent.GetComponent<HunterController>();
if (localPlayerAuthority)
{
print("its a me local player");
if (!shotPos.GetComponent<AudioSource>())
aud = shotPos.gameObject.AddComponent<AudioSource>();
else
aud = shotPos.GetComponent<AudioSource>();
}
else
{
print("client");
}
}
whats the correct way of spawning a gun and assigning it to the local player, i want to spawn the gun because the gun prefab its self has its own shoot logic and i want that logic to be able to make damage to players, thanks.
When a player want to spawn something you should use a [Command] function with NetworkServer.Spawn() inside of it.
[Command] let players send functions to be run at the server.
You then have to use [ClientRpc] to send information from the server to all clients, such as scale, rotation, transform.parent, new components, etc. Make sure to add the prefab to your NetworkManager-component, under “Registered Spawnable Prefabs” and add a NetworkIdentity-component to your gun-prefab.
It would look something like this:
[Command]
void CmdSpawnGun(){
GameObject obj = Instantiate(gunPrefab, transform.position, Quaternion.identity) as GameObject; //sometimes you might have to exchange gunPrefab with Resources.Load(gunPrefab.name, typeof(gameobject))
obj.transform.parent = transform.parent //make the player calling this function the parent
NetworkServer.Spawn(obj);
RpcSetParent(obj, gameObject) //you need to set the parent on all other clients after the object have been spawned
} [ClientRpc]
Please also update your code-sample, it doesn’t include any spawning or instantiating at all, so that’s why it’s not working. Unless your gun is an AudioSource-component?