Spawning GameObject on network, locally change it only on the client that spawned it.
What I want to do: I want a client that spawned as a "Player" to be able to spawn different Vehicles, in the example I have a car and a plane class to choose from. Both vehicle prefabs have specific scripts, one global script that will be enabled on that GameObject for everyone, but also a local script that will ONLY be enabled for the local player that was responsible for spawning that vehicle in the first place. Similarily I also have a camera gameobject attached to each vehicle prefab that is inactive by default that needs to be turned on.
Problem: I can't find a way that let's the client affect the gameobject after it's spawned. At best I only got "isLocalPlayer" to work for the host player, and that was when I tried putting isLocalPlayer inside the [command] method for spawning...
class MyPlayer : NetworkBehaviour
{
public const int CAR = 0;
public const int PLANE = 1;
public GameObject carPrefab;
public GameObject planePrefab;
public Transform spawn;
public GameObject currentVehicle;
void Update()
{
if (!isLocalPlayer)
return;
if (Input.GetButtonDown("Spawn Car"))
CmdSpawn(CAR);
if (Input.GetButtonDown("Spawn Plane"))
CmdSpawn(PLANE);
}
[Command]
public void CmdSpawn(int vehicle)
{
GameObject prefab = (vehicle == CAR ? carPrefab : planePrefab);
GameObject newVehicle = (GameObject)Instantiate(prefab, spawn.position, spawn.rotation);
NetworkServer.Spawn(newVehicle);
}
}
class Plane : NetworkBehaviour
{
public LocalFlightControls local;
public GlobalFlightControls global;
public new GameObject camera;
private void Start()
{
if (isLocalPlayer)
{
local.enabled = true;
camera.SetActive(true);
}
}
}
In this example, isLocalPlayer never gets recognized in the start loop, since any player has a Network Identity, but the vehicles have their own Identities in order for Network Transform to work. I have tried a lot of searching and I'm honestly quite clueless. I also want to somehow set the player's "currentVehicle" variable to reference the vehicle that is currently in use, so that I can destroy it when I want to re-spawn or spawn another one