< I’m developing a simple 2D tank-shooting game. I have a script which uses to (and only to) instantiate and launch a bullet prefab. This script is being called by a script which attached to player named PlayerController() (when press Fire1 button for specific).>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletBehaviourController : MonoBehaviour {
public GameObject bulletLauncher; // This is the Empty GameObject which I attached the script to
public GameObject[] bulletPrefab; // This is the list of prefabs of my bullet. Because my tanks have various types of bullet so I have to use a list and then, via my SystemEventHandler() script, I can change the bullet type dynamically by changing the value of typeOfBullet variable
public int typeOfBullet = 1; // This variable is uses to change the type of bullet
public float force = 15f; // This variable defines how much force to applies on the bullet's instance
private void OnTriggerEnter(Collider touchedGameObject)
{
if (touchedGameObject.gameObject.tag == "CanBeDestroyByBullet")
{
Destroy(touchedGameObject);
// I want to destroy its instance (bulletInstance) here
}
else if (touchedGameObject.gameObject.tag == "CantBeDestroyByBullet")
{
Debug.Log("Hit undstructive GameObject");\
// I want to destroy its instance (bulletInstance) here
}
}
public void BulletLauncher ()
{
GameObject bulletInstance = Instantiate(bulletPrefab[typeOfBullet], bulletLauncher.transform.position, transform.rotation) as GameObject; // I want to destroy this instance
bulletInstance.GetComponent<Rigidbody2D>().AddForce(bulletInstance.transform.up * force, ForceMode2D.Impulse); // This is use to launch the bullet's instance
Destroy(bulletInstance, 5.0f);
}
}
The problem is: I don’t know how to destroy bulletInstance in OnTriggerEnter(). Note that I have assigned Collider2D and Rigidbody2D component on every GameObject and set Collider2D of bullet prefab to Is Trigger. If need I can provide my PlayerController() script, but I don’t think it’s neccesary.
Thanks for your help : )