- Home /
Question by
PjTheIndieDev · May 25, 2017 at 02:56 PM ·
c#gameobjectcolliderdestroydistance
Destroying Game Object On MouseButtonDown + Distance Collision
I would like to destroy a game object when a collision occurs on the object instead of when a user is at any distance and uses MouseButtonDown.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMining : MonoBehaviour {
GameObject Stone;
void MiningStone()
{
if (Input.GetMouseButtonDown(0))
{
//TODO Have Only The Game Object Be Destroyed If Mouse Collision Occurred On The GameObject Stone
//Instead Of All Objects Being Destroyed Upon Mouse Button Down
Destroy(gameObject);
}
}
// Update is called once per frame
void Update () {
MiningStone();
}
}
Comment
Found the solution, but now it destroys every gameObject and not GameObject Stone.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player$$anonymous$$ining2 : $$anonymous$$onoBehaviour {
GameObject Stone;
void $$anonymous$$iningStone()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10f))
{
Debug.DrawRay(ray.origin, hit.point);
Destroy(GameObject.Find(hit.collider.gameObject.name));
}
}
}
// Update is called once per frame
void Update () {
$$anonymous$$iningStone();
}
}