Спавнится много объектов вместо одного Unity 3d
вот такая проблема у меня: Создал пустой объект "Cube Spawner" и прикрепил к нему скрипт "CubeSpawner":
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeSpawner : MonoBehaviour
{
public GameObject cube;
bool ready = false;
Transform pos;
public float delay;
private void Start()
{
pos = GetComponent<Transform>();
StartCoroutine(SpawnCube());
Instantiate(cube);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Cube")
{
ready = false;
}
}
private void OnTriggerStay(Collider other)
{
if (other.tag == "Cube")
{
ready = false;
}
}
private void OnTriggerExit(Collider other)
{
if(other.tag == "Cube")
{
ready = true;
Instantiate(cube);
}
}
IEnumerator SpawnCube()
{
yield return new WaitForSeconds(0.1f);
if (ready == true)
{
float Xpos = pos.position.x;
float Ypos = pos.position.y;
float Zpos = pos.position.z;
ready = false;
Instantiate(cube, new Vector3(Xpos, Ypos, Zpos), Quaternion.identity);
}
StartCoroutine(SpawnCube());
}
}
В начале у меня появляется один куб(всё пока идёт нормально) с анимацией, когда нажимаю "W" куб падает и срабатывает триггер, пропадания объекта со спавнера. Далее появляется 2 куба с анимацией, после нажатия "W" и больше, и больше...

Вот сам скрипт префаба:
using System.Collections.Generic;
using UnityEditor.SceneManagement;
using UnityEngine;
public class Cubecontroller : MonoBehaviour
{
bool _isPlayable;
Rigidbody rb;
private void Start()
{
_isPlayable = true;
rb = GetComponent<Rigidbody>();
}
private void Update()
{
CubeReaction();
}
private void CubeReaction()
{
if (_isPlayable == true && Input.GetKeyDown("w"))
{
_isPlayable = false;
rb.isKinematic = false;
Destroy(GetComponent<Animator>());
}
}
}
Нужно, чтобы спавнился один куб, можете помочь?
Ответы (1 шт):
Автор решения: Yaroslav
→ Ссылка
Схема с коллайдерами и тегами хлипкая, запутанная и не нужная.
[DisallowMultipleComponent]
public class CubeSpawner : MonoBehaviour
{
// поля внутренней кухни не должны быть публичные
// поля SerializeField отражены в инспекторе
[SerializeField] private Cube _cubeTemplate;
// сколько кубу нужно пролететь до спавна следующего
[SerializeField] private float _respawnDeltaY = 1f;
[SerializeField] private KeyCode _fallKey = KeyCode.W;
private Transform _transform;
private Cube _currentCube;
private void Awake ()
{
_transform = transform;
SpawnCurrentCube();
}
private void Update ()
{
if (_currentCube != null && Input.GetKeyDown(_fallKey))
{
_currentCube.Fall();
StartCoroutine(RespawnCubeCoroutine(_currentCube.transform));
_currentCube = null;
}
}
private IEnumerator RespawnCubeCoroutine (Transform target)
{
while (true)
{
if (target.position.y < _transform.position.y-_respawnDeltaY)
break; // выход из цикла
yield return null; // каждый кадр
}
SpawnCurrentCube();
}
private void SpawnCurrentCube ()
{
GameObject NewCube = Instantiate(_cubeTemplate.gameObject);
NewCube.transform.position = _transform.position;
_currentCube = NewCube.GetComponent<Cube>();
}
}
[DisallowMultipleComponent]
[RequireComponent(typeof(Rigidbody))]
public class Cube : MonoBehaviour
{
private Rigidbody _body;
private void Awake ()
{
_body = GetComponent<Rigidbody>();
}
public void Fall ()
{
_body.isKinematic = false;
}
}