I’m trying to implement a dynamic recoil script but it requires me to call the transform of a camera. The “Transform.Find” is what I need but it seems that the GameObject isn’t being properly recognized and I assume it’s because of how I wrote it.
Recoil_Script = transform.Find("CameraRot/CameraRecoil").GetComponent<Recoil>();
When I actually start the game in unity it comes up with NullReferenceException stating that it’s not set to an instance of an object, so I assumed I just called it improperly. I looked over the documentation for Transform.Find and it didn’t seem to enlighten me of my woes and I couldn’t find any solid workaround so I come here to see if I can find a solution.
The full scripts may have more information that I may not have provided here, so the full two scripts will be listed below with hopefully more enlightening details.
{
[Header("References")]
[SerializeField] GunData gunData;
[SerializeField] private Transform muzzle;
[Header("Shot")]
public AudioSource source1;
public AudioClip shot;
[Header("Reload")]
public AudioSource source2;
public AudioClip reload;
float timeSinceLastShot;
private Recoil Recoil_Script;
void Start()
{
Recoil_Script = transform.Find("CameraRot/CameraRecoil").GetComponent<Recoil>();
PlayerShot.shootInput += Shoot;
PlayerShot.reloadInput += StartReload;
}
public void StartReload()
{
if (!gunData.reloading)
{
StartCoroutine(Reload());
}
}
private IEnumerator Reload()
{
gunData.reloading = true;
source2.PlayOneShot(reload, 0.25f);
yield return new WaitForSeconds(gunData.reloadTime);
gunData.currentAmmo = gunData.magSize;
gunData.reloading = false;
}
private bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1f / (gunData.fireRate / 60f);
public void Shoot()
{
if (gunData.currentAmmo > 0)
{
if (CanShoot())
{
Debug.Log("BANG!");
Recoil_Script.RecoilFire();
source1.PlayOneShot(shot, 0.25f);
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hitInfo, gunData.maxDistance))
{
Debug.Log(hitInfo.transform.name);
IDamagable damagable = hitInfo.transform.GetComponent<IDamagable>();
damagable?.Damage(gunData.damage);
}
gunData.currentAmmo--;
timeSinceLastShot = 0;
OnGunShoot();
}
}
}
void Update()
{
timeSinceLastShot += Time.deltaTime;
}
private void OnGunShoot()
{
}
}
{
//Rotation
private Vector3 currentRotation;
private Vector3 targetRotation;
//Hip Recoil
[SerializeField] private float recoilX;
[SerializeField] private float recoilY;
[SerializeField] private float recoilZ;
//Settings
[SerializeField] private float snap;
[SerializeField] private float returnSpeed;
void Start()
{
}
void Update()
{
targetRotation = Vector3.Lerp(targetRotation, Vector3.zero, returnSpeed * Time.deltaTime);
currentRotation = Vector3.Slerp(currentRotation, targetRotation, snap * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRotation);
}
public void RecoilFire()
{
targetRotation += new Vector3(recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ, recoilZ));
}
}