I’m making a space ship game. I have a raycast shooting script attached to the main and only camera. It works fine and destroys the object that the raycast hits. When the player hits a wall and dies; the camera and ships transforms position to a set location at the beginning of the level. However, the raycast section of the shoot script no longer works and I have no idea why. Below is the shoot script.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour
{
bool isShowingLaser = false;
public GameObject Lazer;
void Start()
{
Lazer.renderer.enabled = false;
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
fireLaser();
}
}
void showLaser()
{
if( isShowingLaser ) return;
isShowingLaser = true;
Lazer.renderer.enabled = true;
Invoke("resetLaser",0.05F);
isShowingLaser = false;
}
void resetLaser()
{
Lazer.renderer.enabled = false;
}
void fireLaser()
{
showLaser();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //raycast in direction of mouse position
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100.0f))
{
if(hit.transform.gameObject.tag == "Shootable") //destroy object with tag "Shootable"
{
Destroy(hit.transform.gameObject);
}
}
}
}
When you get a bug like this, put in some Debug.Log() statements to figure out what is going on. Is the raycast failing or is the raycast hitting something that is not Shootable? Output the name and the the tag inside the raycast. Debug.Log(hit.collider.name + " , " + hit.collider.tag);
– robertbuI usually prefer to just
– Benproductions1Debug.DrawRaythe ray with the distance of the hit, so I can both see what it's hitting and what direction it travels :)