Reputation: 65
So I have the map in my game split into different areas. Each are made into a separate array in the Area array. I am currently stuck on being able to click on the object. When the player clicks on the object in the game the part of the map that he clicks on should pop up a certain amount and when he clicks on another part that part should pop up and the other one should do back to its original position. I am currently having that object be destroyed when I click on it, but it won't even be selected in game.
using UnityEngine;
using System.Collections;
public class AreaSelection : MonoBehaviour {
public GameObject[] Areas;
void Start()
{
Areas = new GameObject[20];
}
void Update()
{
}
void OnMouseDown()
{
Destroy(this.gameObject);
}
Upvotes: 1
Views: 214
Reputation: 5108
"OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider."
This means that you need a Collider on the GameObject that this script is attached to. The OnMouseDown will only trigger on the GameObject it's attached to. So if you have this script on some kind of manager that doesn't have a Collider or size or anything, you won't be able to use OnMouseDown. If you'd like to go another route, which I sort of recommend, you'd relocate the logic to the Update()
method sort of like this:
(from a 2d-project of mine) ```
RaycastHit2D hit;
public LayerMask mask;
Vector2 mousePos;
GameObject selectedObject;
void Update() {
// If mouse left click is pressed
if (Input.GetMouseButtonDown(0)) {
mousePos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
hit = Physics2D.Raycast(mousePos, Vector2.zero, mask);
if (hit.collider != null)
{
selectedObject = hit.collider.gameObject;
}
}
}
Note that you have to set the public LayerMask in the inspector to only hit the Objects you want to hit.
With this script you should be able to send a Raycast from your screen towards your mouse and, if it hits any GameObject with the selected Layer in the LayerMask it will put that object in SelectedObject (and once you have the gameobject you can do whatever you want with it).
Upvotes: 3