The first destroy is good. It destroys gameobject on client side and host side. But after the item is spawned again, the destroy method works only on host side. Do u have any suggestions?
This is my logic to destroy gameobject:
using System;
using System.Collections;
using Unity.Netcode;
using UnityEngine;
[Serializable]
public class ItemDroppedInteractable : Interactable
{
[SerializeField] private string interactText;
public Equipment item;
public Inventory _inventory;
public override void OnNetworkDespawn()
{
GameObject.Find("WeaponSpawn").GetComponent<SpawnItem>().SpawnAfterTime(10f);
base.OnNetworkDespawn();
}
public void Interact()
{
PickUpServerRpc();
DestroyServerRpc();
}
public string GetInteractText()
{
return interactText;
}
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Inventory>())
{
this._inventory = other.GetComponent<Inventory>();
gameObject.GetComponent<NetworkObject>().ChangeOwnership(NetworkManager.LocalClientId);
}
}
[ServerRpc(RequireOwnership = false)]
void PickUpServerRpc()
{
try
{
_inventory.AddClientRpc(item);
gameObject.GetComponentInChildren<NetworkObject>().ChangeOwnership(NetworkManager.ServerClientId);
}
catch (Exception e)
{
NetworkLog.LogErrorServer(e.Message);
throw;
}
}
[ServerRpc(RequireOwnership = false)]
void DestroyServerRpc()
{
gameObject.GetComponentInChildren<NetworkObject>().RemoveOwnership();
gameObject.GetComponentInChildren<NetworkObject>().Despawn(true);
NetworkManager.Destroy(gameObject);
Destroy(gameObject);
}
}
This is my logic for spawning gameObject:
using Unity.Netcode;
using UnityEngine;
public class SpawnItem : NetworkBehaviour
{
[SerializeField] private GameObject obj;
public void SpawnAfterTime(float time)
{
Invoke("SpawnItemAfterTime", time);
}
public void SpawnItemAfterTime()
{
GameObject spawnedItem = Instantiate(obj, this.transform);
spawnedItem.GetComponent<NetworkObject>().TrySetParent(gameObject);
spawnedItem.GetComponent<NetworkObject>().DestroyWithScene = true;
spawnedItem.GetComponent<NetworkObject>().Spawn(true);
spawnedItem.GetComponent<NetworkObject>().TrySetParent(gameObject);
spawnedItem.GetComponent<NetworkObject>().ChangeOwnership(NetworkManager.LocalClientId);
}
private void Start()
{
GameObject spawnedItem = Instantiate(obj, this.transform);
spawnedItem.GetComponent<NetworkObject>().Spawn(true);
}
}