How can you spawn objects on network using raycast?
I am creating a multiplayer game that allows players to place blocks to defend themselves. Anyone have an idea on how to do this?
This is the current script
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking;
public class Shooting : NetworkBehaviour {
[SerializeField] public Transform shootLocation;
[SerializeField] public GameObject cannonBall;
[SerializeField] public float shootingSpeed;
[SerializeField] public static int blocks;
[SerializeField] public GameObject cube;
private Vector3 dropLocation;
void Start () {
blocks = 5;
}
void Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
if (blocks > 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name != "null" && hit.transform.name != "wall")
{
dropLocation = new Vector3(hit.point.x, hit.point.y + 1.5f, hit.point.z);
CmdSpawn();
}
}
}
else
{
CmdFire();
}
}
}
[Command]
void CmdSpawn()
{
print("cube");
blocks = blocks - 1;
var block = Instantiate(cube, dropLocation, Quaternion.identity);
NetworkServer.Spawn(block);
}
[Command]
void CmdFire()
{
var shell = Instantiate(cannonBall, shootLocation.position, shootLocation.rotation);
shell.GetComponent<Rigidbody>().velocity = shell.transform.forward * shootingSpeed;
NetworkServer.Spawn(shell);
}
}
Any ideas on why this doesn't work?
I have been struggling on this same problem for about one week. I need to finish this before I can work on the rest of my game. Please help me
Referring to the past code, the console doesn't print "cube", the objects spawn at 0,0,0 and the blocks stay at 5. Anyone know why this happens? I have been stuck on this same thing for the longest time, please help.
Your answer

Follow this Question
Related Questions
How to get OnTriggerEnter working over a network 2 Answers
Bullets not spawning in other clients but its spawning on the client that shot it. 1 Answer
local scale network 0 Answers
NullReferenceException at adding a NetworkTransformChild component 1 Answer
Problem with networking/ Command/ ClientRPC/ multiplayerChat. 0 Answers