Home > Blockchain >  Having trouble calling a ServerRpc function from button - Unity Netcode
Having trouble calling a ServerRpc function from button - Unity Netcode

Time:11-20

I'm trying to spawn a monster when the player click a button but when doing so it return a NullReference. What's weird about it it's that the NullReference point to the first line of the ServerRpc function so even a Debug.Log is considered Null. (The testButton function was created to check if anything was wrong with my button, but it does work fine).

To give more context, the buttons are instantiated when the player spawn. The player is linked to the button from the prefab directly.

enter image description here

The player is able to spawn monsters by pressing A and that's working wonderfully so the all the logic of spawning works fine.

 public class PlayerNetwork : NetworkBehaviour
    {

        private SpawnMonsters spawn;
        
        public MonsterCardGame[] monsterDeck;
        public Transform[] cardEmps;
        
        public override void OnNetworkSpawn()
        {
            spawn = FindObjectOfType<SpawnMonsters>();
        }

        private void Update()
        {
            if (!IsOwner) return;

            if (Input.GetKey(KeyCode.A))
            {
                SpawnMonsterServerRpc();
            }
        }
        

        
        [ServerRpc(RequireOwnership = false)]
        public void SpawnMonsterServerRpc()
        {
            Debug.Log("ServerRpc");
            spawn.SpawnMonster(0);
        }
        
        public void testButton()
        {
            Debug.Log("Clickbutton");
            SpawnMonsterServerRpc();
        }
    }

CodePudding user response:

Adding an EventListener to the button fixed the problem!

  • Related