- Home /
The question is answered, right answer was accepted
Clicking on one object activates other objects
I am trying to create a Minesweeper + clicker/idle game for practice. For now, I can't get the clicking to work properly. I spawned in all objects through code meaning they are all the same prefabs but at different locations. When I click them the code activates for all of them and all of the tiles change to being open. I am not sure if I'm using the wrong click function here, as I know there is also an OnMouseDown() function instead of Input.GetMouseButtonDown(0) but the only one where the code activates is in the second one.
public class TileClick : MonoBehaviour {
public GameObject openTile;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Instantiate(openTile, transform.position, Quaternion.identity);
Object.Destroy(this.gameObject);
}
}
}
That's my clicking detection. While it does detect clicks, as I said before, it detects them for ALL tiles and activates them all. I only want it to activate on one of them. I've seen RayCasting stuff but I really need more explanation on how that thing works (if that's the solution).
Answer by nedas60 · Jun 26, 2017 at 01:48 PM
Aight, found the problem myself. Turns out that I could have ignored RayCasting. The only reason OnMouseDown function didn't work is because my camera was too close to the object. I moved my camera away by JUST 0.01 and it worked just fine. Moved it back and sure enough, it didn't work anymore. Lesson learned, don't have your camera too close to the object.
Answer by ShadyProductions · Jun 26, 2017 at 10:55 AM
Input.GetMouseButtonDown is triggered everytime you click your mousebutton.
You will have to retrieve your MousePosition and by the hand of the position you will have to figure out if you're in the bounds of your opentile's position to know if you're clicking the opentile. The easiest way to do this is use raycasting.
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f)) {
if (hit.collider.gameObject.transform.position = opentile.transform.position)
{
Instantiate(openTile, transform.position, Quaternion.identity);
Object.Destroy(this.gameObject);
}
}
}
That gives me a Null Reference because openTile is what I want to spawn in, not what I have. I want to check if I click on this object, not the object I will instantiate AFTER a click. I tried setting it to this.gameObject but that still gives me an exception.