2

Всем привет, возникла такая проблема, что после нажатия кнопки play, при попытке сделать свайп, unity намертво глохнет и приходится через диспетчер задач её выключать.У меня есть 3 подозреваемых: GameController, скрипт отвечающий за сферу или SwipeController:

using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.EventSystems;

public class GameController : MonoBehaviour
{
    public int speedOfMovement = 20;
    public float speedOfSpawn = 5f;
    public GameObject whatToMove;
    private Transform posOfRocket;
    public Transform spawnZone;
    private Collider MetColl;
    public GameObject objToSpawn;
    float maxZ;
    float nowX = 0f;
    string Direction;
    Sphere sphere;
    void Start() {
            posOfRocket = whatToMove.GetComponent<Transform>(); //получение компонента ракеты
            MetColl = objToSpawn.GetComponent<BoxCollider>(); // получение коллизии метеорита
            StartCoroutine(SpawnMeteorite());
            sphere = objToSpawn.GetComponent<Sphere>();
            Direction = sphere.WhatToDisable;
            SwipeController.SwipeEvent += CheckInput;
    }
    IEnumerator SpawnMeteorite() {
            while(true) {
                SpawnMet();
                yield return new WaitForSeconds(speedOfSpawn);
            }
    }
    private void SpawnMet() {
            maxZ = spawnZone.position.z;  // спавн метеорита
            Vector3 spawnPos = new Vector3(nowX , spawnZone.position.y, maxZ);
            Instantiate(objToSpawn, spawnPos, Quaternion.identity);
    }
    void Update() {
            posOfRocket.Translate(0, speedOfMovement * Time.deltaTime, 0); // движение ракеты
    }
    public void CheckInput(SwipeController.SwipeType type)
    {
        StartCoroutine(WaitForSwipe(type));
    }
    IEnumerator WaitForSwipe(SwipeController.SwipeType dirOfSwipe)
    {
        while (true)
        {
            if (Direction == "up" && dirOfSwipe == SwipeController.SwipeType.UP)
            {
                Debug.Log("up");
            }
            else if (Direction == "down" && dirOfSwipe == SwipeController.SwipeType.DOWN)
            {
                Debug.Log("down");
            }
            else if (Direction == "right" && dirOfSwipe == SwipeController.SwipeType.RIGHT)
            {
                Debug.Log("right");
            }
            else if (Direction == "left" && dirOfSwipe == SwipeController.SwipeType.LEFT)
            {
                Debug.Log("left");
            }
        }
    }
    


}

Sphere:

using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;


public class Sphere : MonoBehaviour
{
    public GameObject LeftText;
    public GameObject RightText;
    public GameObject UpText;
    public GameObject DownText;
    private string[] direction = {"up", "left", "right", "down"};
    private System.Random rnd = new System.Random();
    public string WhatToDisable;
    GameObject gameControler;
    GameController callingMethod;
    private void Start()
    {
        callingMethod = gameControler.GetComponent<GameController>();
    }
    void OnTriggerEnter(Collider col) {
        string dir = direction[rnd.Next(0, 3)];
        if (col.gameObject.tag == "Player") {
            switch (dir) {
                case "up":
                    UpText.SetActive(true);
                    WhatToDisable = "up";
                    break;
                case "left":
                    LeftText.SetActive(true);
                    WhatToDisable = "left";
                    break;
                case "right":
                    RightText.SetActive(true);
                    WhatToDisable = "right";
                    break;
                case "down":
                    DownText.SetActive(true);
                    WhatToDisable = "down";
                    break;
            }}
            Time.timeScale = 0.1f;
            Time.fixedDeltaTime = Time.timeScale * 0.02f;
    }
    void OnTriggerStay(Collider col) {
        if (col.gameObject.tag == "Player") {
            Debug.Log("some text");
        }

    }
    void OnTriggerExit(Collider col) {
        if (col.gameObject.tag == "Player") {
            switch(WhatToDisable) {
                case "up":
                    UpText.SetActive(false);
                    break;
                case "left":
                    LeftText.SetActive(false);
                    break;
                case "right":
                    RightText.SetActive(false);
                    break;
                case "down":
                    DownText.SetActive(false);
                    break;
            }

            Time.timeScale = 1;
            Time.fixedDeltaTime = Time.timeScale * 1;
        }

    }
}

и SwipeController:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwipeController : MonoBehaviour
{
    bool IsDragging, isMobilePlatform;
    Vector2 tapPoint, swipeDelta;
    float minSwipeDelta = 130;
    public enum SwipeType
    {
        LEFT,
        RIGHT,
        UP,
        DOWN
    }
    public delegate void OnSwipeInput(SwipeType type);
    public static event OnSwipeInput SwipeEvent;
    private void Awake() 
    {
        #if UNITY_EDITOR || UNITY_STANDLONE
            isMobilePlatform = false;
        #else
            isMobilePlatform = true;
        #endif
    }


    private void Update()
    {
        if (!isMobilePlatform)
        {
            if (Input.GetMouseButtonDown(0))
            {
                IsDragging = true;
                tapPoint = Input.mousePosition;
            }
            else if (Input.GetMouseButtonDown(0))
            {
                ResetSwipe();
            }
        }
        else
        {
            if (Input.touchCount > 0)
            {
                if (Input.touches[0].phase == TouchPhase.Began)
                {
                    IsDragging = true;
                    tapPoint = Input.touches[0].position;
                }
                else if (Input.touches[0].phase == TouchPhase.Canceled || Input.touches[0].phase == TouchPhase.Ended)
                {
                    ResetSwipe();
                }
            }
        }
        CalculateSwipe();
    }
    void CalculateSwipe()
    {
        swipeDelta = Vector2.zero;
        if (IsDragging)
        {
            if (!isMobilePlatform && Input.GetMouseButton(0))
            {
                swipeDelta = (Vector2)Input.mousePosition - tapPoint;
            }
            else if (Input.touchCount > 0)
            {
                swipeDelta = Input.touches[0].position - tapPoint;
            }
        }
        if (swipeDelta.magnitude > minSwipeDelta)
        {
            if (SwipeEvent != null)
            {
                if (Mathf.Abs(swipeDelta.x) > Mathf.Abs(swipeDelta.y))
                {
                    SwipeEvent(swipeDelta.x < 0 ? SwipeType.LEFT : SwipeType.RIGHT);
                }
                else
                {
                    SwipeEvent(swipeDelta.y > 0 ? SwipeType.UP : SwipeType.DOWN);
                }

            }
            ResetSwipe();
        }
    }
    void ResetSwipe()
    {
        IsDragging = false;
        tapPoint = swipeDelta = Vector2.zero;
    }
    
}

Может кто нибудь подсказать, в чём проблема.

1
  • WaitForSwipe без конечный цикл while.
    – Yaroslav
    18 июл 2020 в 19:42

1 ответ 1

4

В скрипте GameController в самом низу у вас в IEnumerator WaitForSwipe() идет бесконечный цикл while(true), который выводит просто строки в консоль. Из-за этого бесконечного цикла Unity и замирает наглухо.

P.S. Если в этой функции вы просто выводите строки в консоль, то скорее всего делаете это для проверки правильности работы скрипта? Если да, то лучше делать что-то подобное в функции Update, чтобы проверять каждый кадр. Ну или оставить эту функцию, но между итерациями цикла добавить

yield return new WaitForSeconds(int i);

Чтобы программа не висла, а просто выполняла итерацию цикла, ждала i секунд, итерация цикла, ожидание и т.д.

P.P.S. А вообще бесконечные циклы это плохая штука. С ними надо очень аккуратно.

Ваш ответ

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

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