I’m developing a 2d game. In this game i have a lot of blocks and i want to destroy them when i click on them.
I tried to do this with the OnMouseDown method
void OnMouseDown()
{
Destroy(gameObject);
}
For the first 3 blocks this is working very well, but when i click on more blocks it becomes more and more inaccurate and destroys sometimes blocks in the row under the clicked block or is not reacting. Any idea how i can fix this or what’s wrong?
I think what you need to do is send out a raycast on click and if it hits a certain object you call destroy on that object.
Thanks for your tip i tried it with this code, but when i click on a block i always get this error:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:39)
void Update()
{
//this if check for the mouse left click
if (Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//this if checks, a detection of hit in an GameObject with the mouse on screen
if (hit.transform.gameObject hit.transform.gameObject.tag == "Block")
{
Destroy(hit.transform.gameObject);
}
}
}
I think you want to do something like this:
if ( Physics.Raycast(ray, hit))
Before you check the hit – I think the hit is probably null, which is what is causing the crash. I think you also need to instantiate the hit variable itself.
the soenke i have made a video tutorial with raycast click check it out it will help you
the soenke i have made a video tutorial with raycast click check it out it will help you
Thanks for your video. But i still have the problem that after i have destroyed a few blocks it becomes inaccurate and destroys the wrong block. Any idea what could be the problem?
if(Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
target = hit.transform.gameObject;
if(target.tag == "Block")
{
Destroy(target);
}
}
}
Update: Suddenly it’s working, but i have no idea why…
Your original Code should work just fine, there is no need for explicit raycasting here.
Your problem is not within those lines of code, but rather in badly placed colliders or objects within other objects.