0

Как остановить действие скрипта через определенное время?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
    
public class RoomSpawner : MonoBehaviour
{
  public Direction direction;

  public enum Direction
  {
    Top,
    Bottom,
    Left,
    Right,
    None
  }

  private RoomVariants variants;
  private int rand;
  private bool spawned = false;
  private float waitTime = 3f;

  private void Start()
  {
    variants = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomVariants>();
    Destroy(gameObject, waitTime);
    Invoke("Spawn", 0.2f);
    StartCoroutine (walera());
  }
  public void Spawn()
  {
    if(!spawned)
    {
      if(direction == Direction.Top)
      {
        rand = Random.Range(0, variants.topRooms.Length);
        Instantiate(variants.topRooms[rand], transform.position, variants.topRooms[rand].transform.rotation);
      }
      else if(direction == Direction.Bottom)
      {
        rand = Random.Range(0, variants.bottomRooms.Length);
        Instantiate(variants.bottomRooms[rand], transform.position, variants.bottomRooms[rand].transform.rotation);
      }
      else if(direction == Direction.Right)
      {
        rand = Random.Range(0, variants.rightRooms.Length);
        Instantiate(variants.rightRooms[rand], transform.position, variants.rightRooms[rand].transform.rotation);
      }
      else if(direction == Direction.Left)
      {
        rand = Random.Range(0, variants.leftRooms.Length);
        Instantiate(variants.leftRooms[rand], transform.position, variants.leftRooms[rand].transform.rotation);
      }
      spawned = true;
    }
  }
  private void OnTriggerStay2D(Collider2D other)
  {
    if(other.CompareTag("RoomPoint") && other.GetComponent<RoomSpawner>().spawned)
    {
      Destroy(gameObject);
    }
  }
  IEnumerator walera()
  {
    yield return new WaitForSeconds(1);
    // Остановка скрипта
  }
}
Новый участник
Dezert — новый участник сайта. Будьте снисходительны, задавая уточняющие вопросы, комментируя и отвечая. Почитайте про нормы поведения.

1 ответ 1

1

Вы можете просто удалить скрипт и таким образом он больше не будет ничего делать. Вот пример как можно сделать:

private IEnumerator Stop()
{
  yield return new WaitForSeconds(3);
  Destroy(this);
}

Таким образом если вызвать корутину Stop то через 3 секунды экземпляр класса удалится с объекта. А если вам понадоьится еще один скрипт можно добавить его через GameObject.AddComponent<YourScript>();

1
  • Спасибо большое
    – Dezert
    18 сен в 14:42

Ваш ответ

Dezert — новый участник. Будьте дружелюбны к нему и не забывайте про нормы поведения.

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.