- Home /
This question was
closed May 07, 2016 at 05:19 PM by
meat5000 for the following reason:
Duplicate Question - Do a search
Question by
mohamedkhlifi · May 07, 2016 at 04:29 PM ·
instantiatearraydestroy
How to destroy an instantiated object when I touch it?
Hi, I want to destroy intantiated objects before they reach a given target. This is what ObjectPool.cs contains:
using UnityEngine;
using System.Collections; using UnityEngine.UI;
public class ObjectPool : MonoBehaviour
{
GameObject[] projectiles = null;
public int numberOfProjectilesToCreate = 1;
public AudioSource audio1;
// Use this for initialization
void Start ()
{
projectiles = new GameObject[numberOfProjectilesToCreate];
InvokeRepeating ("InstantiateProjectiles", 1f, 0.2f);
}
// Update is called once per frame
void Update () {
ActivateProjectile();
DestroyByTouch ();
}
private void InstantiateProjectiles()
{
for (int i = 0; i < numberOfProjectilesToCreate; i++)
{
projectiles [i] = Instantiate (Resources.Load ("Prefabs/Prefab_projectile")) as GameObject;
}
}
private void ActivateProjectile()
{
for(int i=0; i<numberOfProjectilesToCreate;i++)
{
if (Mathf.Round(projectiles [i].transform.position.y) == 130)
{
projectiles[i].SetActive(false);
}
projectiles[i].SetActive(true);
projectiles[i].GetComponent<projectile>().Activate();
return;
}
}
private void DestroyByTouch()
{
Vector2 touchPos;
for (int j = 0; j < numberOfProjectilesToCreate; j++) {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch (i).phase == TouchPhase.Began) {
if (Input.GetTouch (i).tapCount > 0) {
touchPos = Input.touches[0].position;
Debug.Log (Mathf.Round (touchPos.x)+" , "+Mathf.Round (touchPos.y));
}
}
}
}
}
}
And this is what projectile.cs contains:
using UnityEngine; using System.Collections;
public class projectile : MonoBehaviour {
public float life = 2f;
private float timeToDie = 0.0f;
public Vector3 targetPosition = new Vector3(0,-2.5f,0);
public float speed = 12f;
public float threshold = 0;
// Update is called once per frame
void Update () {
CountDown ();
AutoMove ();
}
public void Activate()
{
timeToDie = Time.time + life;
transform.position = new Vector3 (Random.Range (-6.00f, 6.00f), 9f, 0);
}
private void Deactivate()
{
this.gameObject.SetActive(false);
}
private void CountDown()
{
if(timeToDie<Time.time)
{
Deactivate ();
}
}
private void AutoMove()
{
Vector3 direction = targetPosition - transform.position;
if(direction.magnitude > threshold){
direction.Normalize();
transform.position = transform.position + direction * speed * Time.deltaTime;
}else{
// Without this game object jumps around target and never settles
transform.position = targetPosition;
}
}
}
Comment
Follow this Question
Related Questions
using destroy with an array of GameObjects (C#) 1 Answer
Parenting an instantiated prefab. 1 Answer
Destroying 2D Array of Instantated Objects 2 Answers
Destroying Instantiated Prefab 1 Answer