Error on clicking

Hi there!
I have a problem.
When I’m clicking to move the player, it appears an error saying: “: Object reference not set to an instance of an object” and it also says it is at line 36, wich is this part : “Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);”.

Here is my code:

using System.Collections.Generic;
using Mirror;
using UnityEngine;
using UnityEngine.AI;

public class PlayerMovement : NetworkBehaviour
{
    [SerializeField] private NavMeshAgent agent = null;

    private Camera mainCamera;

    #region Server

    [Command]
    private void CmdMove(Vector3 position)
    {
        if (!NavMesh.SamplePosition(position, out NavMeshHit hit, 1f, NavMesh.AllAreas)) { return; }

        agent.SetDestination(hit.position);
    }

    #endregion

    #region Client

    public override void OnStartAuthority()
    {
        mainCamera = Camera.main;
    }

    [ClientCallback]
    private void Update()
    {
        if (!hasAuthority) { return; }

        if (!Input.GetMouseButtonDown(1)) { return; }

        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        if (!Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity)) { return; }

        CmdMove(hit.point);
    }

    #endregion
}```

Looks like code from the multiplayer course.

Assuming you’re right about the error being on that line, the only thing that makes sense to me is your mainCamera isn’t set. Perhaps you are missing a MainCamera tag on your camera which if I’m not mistaken, would essentially set mainCamera to null and cause an error, but I would have expected a null reference error instead of an object reference not set error.

I’d suspect the error is more about Instantiating a SerializeField GameObject that was from an object in the scene that had since been destroyed.

2 Likes

Thanks man,
The problem was the tag at the camera as you told me.
Thanks again, Tudor.

Glad it worked.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms