In the following script, why is the debug log only showing the text for hitting and/or missing the enemy once:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunController : MonoBehaviour
{
AudioSource audioSource;
public AudioClip clip;
public Transform gunBarrelTransform;
bool triggerPressed = false;
// Use this for initialization
void Start ()
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = clip;
}
// Update is called once per frame
void Update ()
{
if (triggerPressed == false)
{
if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger) || Input.GetMouseButtonDown(0)) // Secondary means Right Hand for Oculus Touch
{
audioSource.Play();
RaycastGun();
triggerPressed = true;
}
}
if (!OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) // Secondary means Right Hand for Oculus Touch
{
triggerPressed = false;
}
}
private void RaycastGun()
{
RaycastHit hit;
if(Physics.Raycast(gunBarrelTransform.position, gunBarrelTransform.forward, out hit))
{
if(hit.collider.gameObject.CompareTag("Enemy"))
{
Debug.Log("Enemy Was Hit");
Destroy(hit.collider.gameObject);
}
else
{
Debug.Log("No Enemy Was Hit");
}
}
}
}
My expectation was that every time I press the fire button it would be doing the raycast check and then updating the debug text to say whether the ray hit or missed an enemy, but it shows the text once for each outcome and then never again, no matter what I shoot or however many times I shoot.
The main code itself seems to work correctly though, because each time I press fire I can kill and destroy different enemies if I shoot at them, and I can fire at walls and hear the shot sound, etc. But the debug info is conflicting with what seems to be happening.
And I think this has been causing me a load of hassle with other code I’ve been trying to set up too, because I assumed the code was broken and re-wrote different versions and deleted them countless times since the debug text wasn’t coming back as expected.