I have a few resource game objects that my players can interact with but now I need to be able to give the players items when they gather. I have a simple system where the local player gets the network id of the object then runs the necessary code to interact with that object.
My question is, how can I get the id of the player that did the interaction? Basically if a player interacts with a gameobject, how do I send that player’s network id to the gameobject so it can send back info like items that are obtained?
I know I’m close, but I’m just not sure how to put all the pieces together. I can get the Network Identity of any object, including players, by using the code:
Debug.Log (netId);
so I can grab the id, but I still am not sure how to send that info to the object, or how to store that info on the object.
Every NetworkBehaviour has a netId field. You can grab the netId from any NetworkIdentity. NetworkIdentitys can be sent in Cmd & Rpc calls where the reciever then get find the corresponding local object on their machine.
The netId is just a uint.
[Command]
public void CmdSendObject(GameObject obj)
Objects sent like this need a NetworkIdentity, so I assume the method just does the work of sending the net id and finding the corresponding object on the receiving side.
An example for gathering:
//(A method on the player)
public void OnPickup(GameObject obj)
{
if (hasAuthority)
{
CmdPickup(obj);
}
}
[Command]
private void CmdPickup(GameObject obj)
{
RpcPickupObj(GameObject obj);
}
[ClientRpc]
private void RpcPickupObj(GameObject obj)
{
if (obj.GetComponent<ItemScript>())
{
obj.GetComponent<ItemScript>().Pickup(this.gameobject);
}
}
//(On ItemScript.This is on any item you can pick up)
public void Pickup(GameObject player)
{
//Do client actions here. i.e. each client gives the player who picked it up the item on their client
player.AddItem(new InventoryItem { some_properties = itemScriptProperties });
if (isServer)
{
//Do server actions here, i.e. destroy the item on the floor
NetworkServer.Destroy(this.gameobject);
}
}