Hi,
I am making a game currently and wanted to figure out how to put a gun into my game,
I followed this tutorial:
watch?v=47ZkulgnadI (put the youtube URL Before cuz it wont let me do another embed)
and it all works perfectly except for the shooting mechanic, where instead the console pumps out tons of errors and says;
NullReferenceException: Object reference not set to an instance of an object
DamageGun.Shoot () (at Assets/Scripts/DamageGun.cs:20)
UnityEngine.Events.InvokableCall.Invoke () (at <779cc116a5954f1c9b92496e62345641>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <779cc116a5954f1c9b92496e62345641>:0)
Gun.Update () (at Assets/Scripts/Gun.cs:31)
This is DamageGun script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageGun : MonoBehaviour
{
public float Damage;
public float BulletRange;
private Transform PlayerCamera;
// Start is called before the first frame update
private void Start()
{
PlayerCamera = Camera.main.transform;
}
// Update is called once per frame
public void Shoot()
{
Ray gunRay = new Ray(PlayerCamera.position, PlayerCamera.forward);
if (Physics.Raycast(gunRay, out RaycastHit hitInfo, BulletRange))
{
if (hitInfo.collider.gameObject.TryGetComponent(out Entity enemy))
{
enemy.Health -= Damage;
}
}
}
}
And here is my Gun script:
using UnityEngine.Events;
using UnityEngine;
public class Gun : MonoBehaviour
{
public UnityEvent OnGunShoot;
public float FireCooldown;
public bool Automatic;
private float CurrentCooldown;
// Start is called before the first frame update
void Start()
{
CurrentCooldown = FireCooldown;
}
// Update is called once per frame
void Update()
{
if (Automatic)
{
if (Input.GetMouseButton(0))
{
if (CurrentCooldown <= 0f)
{
OnGunShoot.Invoke();
CurrentCooldown = FireCooldown;
}
}
}
else
{
if (Input.GetMouseButtonDown(0))
{
if (CurrentCooldown <= 0f)
{
OnGunShoot?.Invoke();
CurrentCooldown = FireCooldown;
}
}
}
CurrentCooldown -= Time.deltaTime;
}
}
Now the error says that either script is not referencing the object that its attatched to right?
However I have attatched the script to my gun object:
But it still thinks that I have no object attatched to the reference which I do not understand.
Any help would be much appreciated, thank you.