Hi. I am currently making an FPS game, and I made a simple shooting script and projectile script. However, when I shoot at the skybox, I get a Null Reference Exception error since my hit
variable returns null each time I shoot a ray to the skybox. My Projectile and Shooting script are shown below:
Projectile Script:
using UnityEngine;
public class Projectile : MonoBehaviour
{
private float _speed;
private Vector3 _target;
public void StartMovingTowards(Vector3 target, float speed)
{
_target = target;
_speed = speed;
}
public void FixedUpdate()
{
transform.position = Vector3.MoveTowards(transform.position, _target, _speed);
}
}
Shooting Script:
using UnityEngine;
public class Shooting : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 1f;
public float impactForce = 30f;
public float projectileSpeed = 1f;
public Camera fpsCam;
public Transform firePoint;
public GameObject projectile;
private RaycastHit hit;
private float nextTimeToFire = 0f;
private void Update()
{
if (Input.GetButton("Fire1") && nextTimeToFire <= Time.time)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
// Every Time I shoot, I want to Instantiate the bullet and move it
GameObject proj = Instantiate(projectile, firePoint);
var movement = proj.GetComponent<Projectile>();
movement.StartMovingTowards(hit.transform.position, projectileSpeed);
}
}
void Shoot()
{
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
}
}
}
So what I want is that even if I’m facing the skybox, the bullet will fire. However, that doesn’t happen, since hit = null
when I’m facing the skybox since the skybox isn’t a GameObject with a collider. So I do know why the error is coming, but I do not know how to tweak the code to perform how I want it. Thanks to anyone who answers.