Answer the question
In order to leave comments, you need to log in
Why is the new spawned object removed?
I have an array of objects, I'm spawning them via InvokeRepeating, and I need to delete the object when it touches the collider.
I create a clone of an object prefab, then this clone, when it touches the collider, it is not deleted, but the clone that just spawned in another place is deleted, I can’t find a solution anywhere, please
help ItemSpawn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemSpawn : MonoBehaviour
{
public GameObject[] clothes; //объекты, кторые надо спавнить
public Transform objspawn;// координата для спавна
public float spawnrate;//частота спавна
public float speed;// скорость движения объекта
public int rand;//рандом для clothes
public GameObject duplObj; //клон clothes
public int i;
void Start()
{
//спавн объектов через заданное время spawnrate
InvokeRepeating("SpawnObj", 1f, spawnrate);
}
void Update()
{
i = rand;
}
void SpawnObj()
{
//сам спавн
rand = Random.Range(0, clothes.Length);
//тут создается клон объекта
duplObj= Instantiate(clothes[i], objspawn.position, transform.rotation);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemMovement : MonoBehaviour
{
ItemSpawn itemSpawn;
void Start()
{
itemSpawn = GameObject.Find("Main Camera").GetComponent<ItemSpawn>();//для определения нахождения скрипта на объекте
}
private void FixedUpdate()
{
transform.Translate(itemSpawn.speed * Time.deltaTime, 0, 0);//движение объекта
}
//Здесь происходит уничтожение клона, если он соприкасается с объектом, у которого тег Destroy
private void OnTriggerEnter2D(Collider2D collis)
{
if (collis.gameObject.tag == "Destroy")
{
Destroy(itemSpawn.duplObj);
}
}
}
Answer the question
In order to leave comments, you need to log in
Here's what I found out, and this: if you delete the clone before the specified amount of spawnrate has passed, then the new clone is deleted.
But how to fix it
, I even tried through the coroutine, but everything is the same
You seem to be constantly updating the duplObj variable during spawn. As a result, it always points to the newly created object, which you delete in ItemMovement.OnTriggerEnter2D
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question