I am trying to make a 3rd person shooter but keep getting an error right at my line about raycasting. I am trying to raycast from the center with a small ball representing where the ray lands
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class Camera : MonoBehaviour
{
public Transform orientation;
public Transform player;
public Transform playerObj;
public Rigidbody rb;
public float rotationSpeed;
[SerializeField] private LayerMask aimColliderLayerMask = new LayerMask();
[SerializeField] private Transform debugTransform;
public CameraStyle currentStyle;
UnityEngine.Camera cam;
public Transform CombatLookAt;
public enum CameraStyle
{
Basic,
Combat
}
void Start()
{
currentStyle = CameraStyle.Combat;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;
if (currentStyle == CameraStyle.Basic)
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 inputDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
if (inputDir != Vector3.zero)
{
playerObj.forward = Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
}
}
else if (currentStyle == CameraStyle.Combat)
{
Vector3 dirToCombatLookAt = CombatLookAt.position - new Vector3(transform.position.x, CombatLookAt.position.y, transform.position.z);
orientation.forward = dirToCombatLookAt.normalized;
playerObj.forward = dirToCombatLookAt.normalized;
}
Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
Ray ray = cam.ScreenPointToRay(screenCenterPoint);
if(Physics.Raycast(ray, out RaycastHit raycastHit, 999f, aimColliderLayerMask))
{
transform.position = raycastHit.point;
debugTransform.position = raycastHit.point;
}
}
}
The error occurs at the "Ray ray =cam.ScreenPointtoRay" line and states that the object reference is not set to an instance of the object. I tried switching "cam.ScreenPointtoRay" to "Camera.main.ScreenPointtoRay" but that also does not work