I want to create a multiplayer shooter. I wrote this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MultiWeapon : MonoBehaviour
{
PhotonView view;
public GameObject bullet;
public Camera mainCamera;
public Transform spawnBullet;
public float shootForce;
public float spread;
public AudioSource _audio;
private void Awake() {
view = GetComponent<PhotonView>();
_audio = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
Shoot();
}
private void Shoot()
{
_audio.Stop();
Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75);
Vector3 dirWithoutSpread = targetPoint - spawnBullet.position;
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
Vector3 dirWithSpread = dirWithoutSpread + new Vector3(x, y, 0);
GameObject currentBullet = Instantiate(bullet, spawnBullet.position, Quaternion.identity);
currentBullet.transform.forward = dirWithSpread.normalized;
currentBullet.GetComponent<Rigidbody>().AddForce(dirWithSpread.normalized * shootForce, ForceMode.Impulse);
_audio.time = 0.15f;
_audio.Play();
}
}
When I launch the game from two devices, this happens: when shooting from the first device, both players shoot, while shooting is not visible on the second device. How to fix it?
To fix this issue, you should modify your Shoot method to check if the PhotonView attached to the GameObject is owned by the local player before processing the shoot action. Here is how you can modify your code:
By adding view.IsMine in the condition, you're ensuring that the shooting action is only performed if the PhotonView is controlled by the local player.
Additionally, you need to make sure that when Instantiate is called to create a bullet, it should be done over the network so that all players can see it. You should use Photon's instantiation method to do this, as follows:
This will ensure that the bullet is created across the network in all clients' games. Note that for this to work, the bullet prefab must be in a "Resources" folder and properly set up in Photon's settings to be network-aware.
Lastly, make sure that your bullet prefab has a PhotonView component attached to it and a script that syncs its position and destruction across the network. Without proper synchronization, other players might not see the bullets or their effects correctly.
Hope help this answer for you