I created multiple same prefab clones like that. and I want to destroy one of them which i select.
First of all i used raycast2d for detecting hit and collied with prefab
if(Input.GetMouseButtonDown(1))
{
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.mousePosition)), Vector2.zero);
if(hit.collider != null && hit.collider.gameObject==gameObject){
health-=PlayerScript.damage;
if(health<=0){
Destroy(hit.collider.gameObject);
}
}
}
this script effect all prefabs health. So i decided create a game object with collider and if this game object collied with prefab , prefab lose health and then destroy. I instantiate the game object like this
GameObject object=Instantiate(selectOb,Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity) as GameObject;
And i check if is there collision between game object and prefab with void OnCollision2DEnter().
Now there is different problem. The game object doesn't collied with other prefab because area sizes of collider
I hope , i could describe my problems. I waiting your advice about selecting specific prefab or my collision problem
Something like this on a gameobject in the scene (probably an empty gameobject that serves as controller):
Note that the direction of the raycast should be -Vector2.up
if you use the default camera orientation.
public class RayShooter : MonoBehaviour
{
void Update()
{
if(Input.GetMouseButtonDown(1)) // 1 is rightclick, don't know if you might want leftclick instead
{
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.mousePosition)), -Vector2.up);
if(hit.collider != null)
{
GameObject target = hit.collider.gameObject;
target.GetComponent<Enemy>().dealDamage(PlayerScript.damage);
// "Enemy" is the name of the script on the things you shoot
}
}
}
}
On the things you shoot (here called "Enemy"):
public class Enemy : MonoBehaviour
{
int health = 10;
public void dealDamage(int value)
{
health -= value;
if(health <= 0)
{
Destroy(gameObject);
}
}
}
This would be a very basic setup, obviously your things to shoot need a collider for this to work. Additionally it might be a good idea to include layers and a layermask to the raycast.