Problem with spawning game object on mouse click

NullReferenceException: Object reference not set to an instance of an object
GameController.Update () (at Assets/ExampleAssets/Scripts/GameController.cs:31)

basically, it says that the error is at this line

Vector3 spawnPos = Camera.main.ScreenToWorldPoint(mousePos);

I gave the mousePos a value by giving it Input.mousePosition but it still gives me this error chatGPT and black-box none have been able to help me out

I would really appreciate your help people

using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : MonoBehaviour
{
    public GameObject ball;
    public Transform spawnPoint;
    // Start is called before the first frame update
    void Start()
    {
        //Spawnball();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Spawnball();
        }

        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            
            mousePos.z = 10f;

            Vector3 spawnPos = Camera.main.ScreenToWorldPoint(mousePos);

            Instantiate(ball, spawnPos, Quaternion.identity);


        }
    }

    void Spawnball()
    {
        Instantiate(ball, spawnPoint.position, Quaternion.identity);
    }
}

2 Answers

2

Try to isolate your problem by using Debug.Log() for this type of situation.

The following line you are using is working properly for me event if a Vector2 can be easier to use with the mouse.
Vector3 mousePos = Input.mousePosition;

So I guess the issue comes from Camera.main

  • Look if you have a camera in your scene
  • Look the tag of your camera, it should be MainCamera
  • Otherwise assign your camera with a variable should work:
public Camera cam;
cam.ScreenToWorldPoint(mousePos);

I will try it out rn