- Home /
Spawning object at wrong location
Hi, I'm trying to have an object be spawned where the player is looking at on a key press. When the host presses the spawn key, everything works fine. The clients on the other hand have their objects spawned at coordinates (0,0,0) instead of where the player is looking at. Here is the code:
public class PlaceGuard : NetworkBehaviour
{
private Camera MainCamera;
private int layerMask = 1 << 8;
public GameObject TrapPrefab;
[SyncVar]
private Vector3 HitLocation;
void Start()
{
MainCamera = GetComponentInChildren<Camera>();
}
void Update()
{
CastRay();
}
void CastRay()
{
//Spawning BearTrap
if (Input.GetKeyDown(KeyCode.T))
{
Ray ray = MainCamera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit, 3.0F, layerMask))
{
HitLocation = hit.point;
CmdSpawnTrap();
}
}
}
[Command]
void CmdSpawnTrap()
{
GameObject Trap = (GameObject)Instantiate(TrapPrefab, HitLocation, Quaternion.identity);
NetworkServer.SpawnWithClientAuthority(Trap, connectionToClient);
}
}
I'd appreciate any help.
Is it possible that you need to wait one frame with CmdSpawnTrap(), because HitLocation's value will only be synched at the end of the frame (as described in https://docs.unity3d.com/ScriptReference/Networking.SyncVarAttribute.html)?
But it is just an ide; I have no experience with unity network program$$anonymous$$g, so it is absolutely possible that [Command] already has that in $$anonymous$$d and the execution on the client is delayed accordingly.
I tried setting up a coroutine to wait for a frame before calling the CmdSpawnTrap funtion, unfortunately that didn't work, the result is still the same. Any other ideas?
Answer by Nooke · Feb 25, 2017 at 05:13 PM
After alot of tial and error I finally found my mistake, I'll post the answer if someone encounters the same problem:
The solution was to add the Vector3 HitLocation variable as a parameter of the CmdSpawnTrap funtion.
Answer by RensDevolp · Feb 21, 2017 at 09:49 AM
I think you have to use Network.instantiate (Network.Instantatiate) As far as I know, this syncs its position with other ones. Also make sure you have an RPC attached to the trap (at least that is how it works with photon)
Isn't that what the code at line 37 does? When you say RPC do you mean a network identity component? Or a command/ClientRpc attribute to be put somewhere in my code?
With photon you have a script called "PhotonRPC". If you put the transform as the observed component, it will sync with the rest of the players
yeah that sounds like the network Transform in unet, I do have that component attached to my trap though.