- Home /
How can I add the OnTriggerEnter function to all 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; float aux1,aux2; bool isMoving = false; Vector2 dir, pos; GameObject gasoline; Rigidbody2D gasolineRB; BoxCollider2D gasolineCol;
void Start()
{
SpawnCoins();
}
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;
gasoline.AddComponent<Rigidbody2D>();
gasolineRB = gasoline.GetComponent<Rigidbody2D>();
gasolineCol=gasoline.GetComponent<BoxCollider2D>();
dir = (pos - new Vector2(-2.7f, 0.1f) ).normalized;
}
//rotation
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.gameObject.tag == "Coin")
{
Destroy(collider.gameObject);
SpawnCoins();
}
if (collider.gameObject.tag == "Border")
{
Destroy(gameObject);
}
}
}
You could make a script with the OnTriggerEnter
method and add that to the GameObject
after instantiating it.
Answer by akaBase · Nov 16, 2019 at 04:35 PM
To further my comment here is an example OnTriggercomponent
script and its usage.
Example OnTriggerEnterComponent
public class OnTriggerEnterComponent : MonoBehaviour
{
public string ActionableTag { get; set; }
private void OnTriggerEnter2D(Collider collision)
{
if (collision.CompareTag(ActionableTag))
{
// Do Something
}
}
}
Demo of its usage
public class Demo : MonoBehaviour
{
public GameObject prefab;
private void Start()
{
GameObject go = Instantiate(prefab, Vector3.zero, Quaternion.identity);
go.AddComponent<BoxCollider2D>();
go.GetComponent<BoxCollider2D>().isTrigger = true;
go.AddComponent<OnTriggerEnterComponent>().ActionableTag = "Player";
}
}
Also as you can see i changed it to use CompareTag
as it is more efficient., Hope this helps.
Your answer
Follow this Question
Related Questions
Hi! How can I use the OnTriggerEnter2D function for the game objects that I instantiate? 3 Answers
How can I check if an instantiated object collides with another instantiated object? 1 Answer
Creating a GameObject variable without instantiating it? 1 Answer
How can I spawn gameObjects within a circle radius? 1 Answer
C# 2d Instantiate object randomly around gameobject 1 Answer