Question by
Bentley100 · Sep 20, 2020 at 12:05 AM ·
c#scripting problemprefabcollision2dcloned
Delete prefab clone when collided with the player, Unity 2D
Hi, I am trying to to delete a clone prefab when the player collides with it in unity 2D. I have been looking all over the internet and none of the scripts work. This is the script collider script that I attached to the player.
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.CompareTag("Player"))
Debug.Log("Col");
}
This is the script I use t spawn the game objects,
{
public int numberToSpawn;
public List<GameObject> spawnPool;
public GameObject quad;
void Start()
{
spawnFood();
}
public void spawnFood()
{
int randomiteam = 0;
GameObject toSpawn;
MeshCollider c = quad.GetComponent<MeshCollider>();
float screenX, screenY;
Vector2 Pos;
for(int i = 0; i < numberToSpawn; i++)
{
randomiteam = Random.Range(0, spawnPool.Count);
toSpawn = spawnPool[randomiteam];
screenX = Random.Range(c.bounds.min.x, c.bounds.max.x);
screenY = Random.Range(c.bounds.min.y, c.bounds.max.y);
Pos = new Vector2(screenX, screenY);
Instantiate(toSpawn, Pos, toSpawn.transform.rotation);
}
}
private void destroyObjects()
{
foreach(GameObject o in GameObject.FindGameObjectsWithTag("spawnFood"))
{
Destroy(o);
}
}
}
Also this script is in c#. Thanks.
Comment
Best Answer
Answer by doublelift41 · Sep 20, 2020 at 10:20 AM
Did you add this to the player gameobject? Why are you looking for the player if you add this to player gameobject?
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.CompareTag("Player"))
Debug.Log("Col");
}
This way you should to use.
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.CompareTag("spawnFood"))
Destroy(collision.gameObject);
}