# Hi! How can I use the OnTriggerEnter2D function for the game objects that I instantiate?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GasolineScript : MonoBehaviour
{

``````public GameObject Gasoline;
public GameObject Coin;
int n = 0, moveSpeed = 6, ok, score = 0;
float aux1,aux2;
bool isMoving = false;
Vector2 dir, pos;
GameObject gasoline;
Rigidbody2D gasolineRB;
BoxCollider2D gasolineCol;

void Update()
{
if (isMoving)
{
gasolineRB.MovePosition(gasolineRB.position + dir * moveSpeed * Time.fixedDeltaTime);
}

if (Input.GetMouseButtonDown(0))
{

gasoline = Instantiate(Gasoline, new Vector2(-2.7f , 0.1f), Quaternion.Euler(0f, 0f, 180f)) as GameObject;
pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
isMoving = true;

//getting direction
gasolineRB = gasoline.GetComponent<Rigidbody2D>();
dir = (pos - new Vector2(-2.7f, 0.1f)).normalized;

//setting collider
gasolineCol= gasoline.GetComponent<BoxCollider2D>();

}

//rotating object
transform.eulerAngles = new Vector3(0, 0, n);
n++;
}

void SpawnCoins()
{
aux1 = Random.Range(-3.9f, -1.55f);
aux2 = Random.Range(-0.9f, 0.9f);
ok = 1;
for(;ok==1;)
{
ok = 0;
if((aux1>=-3f && aux1<=-2.4f) && (aux2<=0.4f && aux2 >= -0.2))
{
ok = 1;
}
if (ok == 1)
{
aux1 = Random.Range(-3.9f, -1.55f);
aux2 = Random.Range(-0.9f, 0.9f);
}
}

GameObject coin= Instantiate(Coin, new Vector2(aux1,aux2), Quaternion.identity) as GameObject;
}

void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("Coin"))
{
Destroy(collider.gameObject);
SpawnCoins();
}

if (collider.CompareTag("Border"))
{
Destroy(gameObject);
isMoving = false;
}

if (collider.CompareTag("Car"))
{
hScript.health = 100;
Destroy(gameObject);
isMoving = false;
score++;
}
}
``````

}

I am trying to check if the instantiated object collides with another object but I don’t know how to do it.

Hi @Mudu_ , i don’t know if your BoxCollider2D is correctly configured, but remember that when you’re working using OnTriggerEnter2D or OnTriggerEnter, you should set the isTrigger to true:
The line wich contains

`````` gasolineCol= gasoline.GetComponent<BoxCollider2D>();
``````

should be like this:

``````gasolineCol= gasoline.GetComponent<BoxCollider2D>();
gasolineCol.isTrigger = true;
``````

Otherwise that little piece of code is just getting the BoxCollider…

However if this seems not to work, it will be good if you post the error you’re getting.

Hi! I don’t know if this is what you meant but I hope this helps (also I might be wrong because I am sorta new to unity so :I): Make another script on the object (prefab) you want to instantiate and detect collisions there.

You could just cast a collider with the same size of the prefab you’re about to instantiate, this way you’ll know before you instantiate something if there’s something already in the place you’re instantiating… you should use some layers and stuff like that to filter but you’ll know it before instantiating