- Home /
Destroy object with tag array OnTriggerEnter C#
I am trying to destroy objects with different tag when the objects enter trigger area. The code below does not work. I am just a beginner and i hope someone can help.
c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class IngredientCheck : MonoBehaviour {
string[] tags;
List<GameObject> CorrectIngredients = new List<GameObject>();
public AudioSource correctfx;
public AudioSource wrongfx;
// Use this for initialization
void Start ()
{
tags = new string[] {"Mungbeans","BananaLeaf","GlutinousRiceflour" };
foreach (GameObject go in GameObject.FindObjectsOfType(typeof(GameObject)))
{
if (tags.Contains(go.tag))
CorrectIngredients.Add(go);
}
}
// Update is called once per frame
void Update ()
{
}
void OnTriggerEnter (Collider col)
{
if (col.gameObject(CorrectIngredients))
{
Destroy(col.gameObject, 2.0f);
correctfx.Play();
}
else
{
wrongfx.Play();
}
}
}
Answer by Positive7 · Sep 30, 2017 at 07:33 PM
Something like this should work :
using System.Linq;
using UnityEngine;
public class IngredientCheck : MonoBehaviour
{
private string[] tags;
public AudioSource Correctfx;
public AudioSource Wrongfx;
private void Start()
{
tags = new[] { "Mungbeans", "BananaLeaf", "GlutinousRiceflour" };
}
private void OnTriggerEnter(Collider col)
{
if (tags.Any(col.CompareTag))
{
Destroy(col.gameObject, 2.0f);
Correctfx.Play();
}
else
{
Wrongfx.Play();
}
}
}
or if you don't want to use Linq :
using UnityEngine;
public class IngredientCheck : MonoBehaviour
{
private string[] tags;
public AudioSource Correctfx;
public AudioSource Wrongfx;
private void Start()
{
tags = new[] { "Mungbeans", "BananaLeaf", "GlutinousRiceflour" };
}
private void OnTriggerEnter(Collider col)
{
var any = false;
foreach (var s in tags)
{
if (col.tag == s)
{
any = true;
}
}
if (any)
{
Destroy(col.gameObject, 2.0f);
Correctfx.Play();
}
else
{
Wrongfx.Play();
}
}
}
Hi, thanks for your reply. It worked, but only work with one object for that tag. I have multiple objects that shared the same tag. I want any object that shared the same tag can be destroy when enter trigger area.
Yes, yes! the updated answer is the one i looking for.Thanks for your help!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I'm trying to adjust tagged objects meshrenderer in C# code. 1 Answer
What's wrong with my code? C# 1 Answer