- Home /
raycast destroying player?
ive made a script that is supposed to destroy a gameobject if the gameobject is clicked on (using raycast and Destroy) but no matter where I click on screen it destroys the player object
if (Input.GetMouseButtonDown (0)) {
Vector3 c = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit2d = Physics2D.Raycast (transform.position, c - transform.position);
if (hit2d.collider.gameObject != null) {
Destroy (hit2d.collider.gameObject);
}
}
Answer by Jwizard93 · Jul 13, 2017 at 04:46 PM
if (Input.GetMouseButtonDown (0)) {
Vector3 c = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit2d = Physics2D.Raycast (c, Camera.main.transform.forward);
if (hit2d.collider.gameObject != null) {
Destroy (hit2d.collider.gameObject);
}
}
You want the ray to start at the mouse and go directly into the screen right? use this instead.
maybe even just transform.forward would work. Any global vector which points into the scene. At the time of posting your ray started at the player. It probably only took a single physics update for the ray to register it was hitting the player (because it was inside the player)
Answer by sid_devic · Jul 13, 2017 at 02:47 PM
You could use something like an if statement to check if the name of the hit gameobject is your player, and if it is then don't destroy the gameobject. Another thing you could do is to check if the gameobject you hit is the one you want to destroy by cross referencing it's name as well. However, checking the name every frame is not recommended, so you should do something like this.
thanks for the suggestion, but it seems no matter where I click it destroys the player, and blocking it from destroying the player still wouldn't completely fix it
I'm confused here. I was under the impression that searching for a GameObject by its tag came with a bigger performance hit than comparing two strings.
Is this script on your player? If the ray starts on your player then you can guarantee the player will be the first thing hit. It looks to me like the ray starts on whatever gameObject this script is on and goes towards the point of click.
I tested your idea with if statement, while the player was not destroyed the objects I clicked on weren't either