Exemple #1
0
    public void Teleport(string teleportPayload)
    {
        ResetGround();

        var payload = Utils.FromJsonWithNulls <Vector3>(teleportPayload);

        var newPosition = new Vector3(payload.x, payload.y, payload.z);

        SetPosition(newPosition);

        if (OnPositionSet != null)
        {
            OnPositionSet.Invoke(characterPosition);
        }

        if (!initialPositionAlreadySet)
        {
            initialPositionAlreadySet = true;
        }
    }
        /// <summary>
        /// Reads a file from a path then calls a given action with the whole file string as the first argument
        /// </summary>
        /// <param name="fpath"></param>
        /// <param name="callback"></param>
        public void ReadFileString(string fpath, System.Action <string> callback)
        {
            string data;

            try
            {
                StreamReader reader = new StreamReader(fpath);
                data = reader.ReadToEnd();
                reader.Close();
            }
            catch (FileNotFoundException)
            {
                string message = string.Format("File not found in {0}!", fpath);
                Debug.LogWarning(message);
                return;
            }

            System.Action action = new System.Action(() => callback.Invoke(data));
            executeOnMainThreadQueue.Enqueue(action);
        }
    IEnumerator CrossFadeAlphaCOR(Image img, float alpha, float duration, System.Action action)
    {
        Color currentColor = img.color;

        Color visibleColor = img.color;

        visibleColor.a = alpha;

        float counter = 0;

        while (counter < duration)
        {
            counter  += Time.deltaTime;
            img.color = Color.Lerp(currentColor, visibleColor, counter / duration);
            yield return(null);
        }

        //Done. Execute callback
        action.Invoke();
    }
Exemple #4
0
        public override void Execute(ITerminalCommandChannel terminalCommandChannel, System.Action <string> prompt)
        {
            if (terminalCommandChannel is BookmarkTerminalCommandChannel)
            {
                Handled = true;

                var bookmarkTerminalCommandChannel = terminalCommandChannel as BookmarkTerminalCommandChannel;

                var bookmarkPage = bookmarkTerminalCommandChannel.BookmarkContainer.CurrentPage;

                if (TerminalCommandLine.ContainKeys("kw"))
                {
                    Result = bookmarkPage.GetItemsByKeyword(TerminalCommandLine["kw"]);
                }
                else
                {
                    prompt.Invoke("keyword is empty.");
                }
            }
        }
Exemple #5
0
 private void UpdateMovement(float detal)
 {
     if (m_IsMove)
     {
         m_MoveTimeTick += detal;
         float   progress = Mathf.Clamp01(m_MoveTimeTick / m_MoveDuration);
         float   hoffset  = m_Rad * Mathf.Sin(Mathf.PI * progress);
         Vector3 pos      = m_MoveForm * (1 - progress) + progress * m_MoveTo;
         pos.y        += hoffset;
         this.position = pos;
         if (progress >= 1)
         {
             m_IsMove = false;
             if (m_Callback != null)
             {
                 m_Callback.Invoke();
             }
         }
     }
 }
Exemple #6
0
        private IEnumerator OnSoundComplete(Sound sound, System.Action <Sound> onComplete)
        {
            // Wait for sound to (theoretically) be over
            AudioSource source = sound.source;

            yield return(new WaitForSeconds(source.clip.length));

            // Notify callback, if supplied
            if (onComplete != null)
            {
                onComplete.Invoke(sound);
            }

            // Move audio source from busy to open pool
            if (sound.usePool)
            {
                busyPool.Remove(source);
                openPool.Add(source);
            }
        }
Exemple #7
0
        static IEnumerator doCallWithDelay(System.Action call, float delay)
        {
            if (delay <= 0)
            {
                yield return(null);
            }
            else
            {
                float start = Time.realtimeSinceStartup;
                while (Time.realtimeSinceStartup < start + delay)
                {
                    yield return(null);
                }
            }

            if (call != null)
            {
                call.Invoke();
            }
        }
    public virtual void Die()
    {
        GameObject           tempGO = Instantiate(onDieParticles, transform.position, Quaternion.identity);
        ParticleSystemTemper tempPS = tempGO.GetComponent <ParticleSystemTemper>();

        if (tempPS != null)
        {
            tempPS.Play();
        }

        if (onDieAction != null)
        {
            onDieAction.Invoke();
        }
        if (GravityController.gravEmitters.ContainsKey(gameObject))
        {
            GravityController.gravEmitters.Remove(gameObject);
        }
        Destroy(gameObject);
    }
Exemple #9
0
    void DrawSettingsEditor(Object settings, System.Action onSettingUpdated, ref bool foldOut, ref Editor settingsEditor)
    {
        if (settings != null)
        {
            foldOut = EditorGUILayout.InspectorTitlebar(foldOut, settings);
            using (var check = new EditorGUI.ChangeCheckScope())
            {
                if (foldOut)
                {
                    CreateCachedEditor(settings, null, ref settingsEditor);
                    settingsEditor.OnInspectorGUI();

                    if (check.changed)
                    {
                        onSettingUpdated.Invoke();
                    }
                }
            }
        }
    }
Exemple #10
0
    public void             GetDirtyDatas(System.Action <string, float[]> Enumerate)
    {
        if (Datas == null)
        {
            return;
        }

        foreach (var NameAndData in Datas)
        {
            var Name       = NameAndData.Key;
            var Data       = NameAndData.Value;
            var DirtyDatas = Data.PopDirtyValues();
            if (DirtyDatas == null)
            {
                continue;
            }

            Enumerate.Invoke(Name, DirtyDatas);
        }
    }
        /// <summary>
        /// Upgrade Rocket Launcher / Magazine
        /// </summary>
        /// <param name="callback"></param>
        public void UpgradeMagazine(System.Action <bool> callback)
        {
            int nextMagLevel = Shop.GetNextMissileMagLvl(m_ShooterData.Amor.MissileMagazineLvl);

            if (nextMagLevel == -1)
            {
                return;
            }

            int upgradeCost = Shop.GetMissileMagUpgrdCost(nextMagLevel);

            if (m_ShooterData.CoinsInHand >= upgradeCost)
            {
                m_ShooterData.CoinsInHand            -= upgradeCost;
                m_ShooterData.Amor.MissileMagazineLvl = nextMagLevel;
                m_ShooterData.Amor.MagazineCapacity   = Shop.GetMagazineCapacityByLvl(nextMagLevel);
                SaveData();
                callback.Invoke(true);
            }
        }
Exemple #12
0
        //either started manually from LocalCache.UploadAllLocalData or from successful 200 response from current session data
        void LoopUploadFromLocalCache()
        {
            if (isuploadingfromcache)
            {
                return;
            }

            if (lc.CanReadFromCache())
            {
                isuploadingfromcache = true;
                string url     = "";
                string content = "";
                lc.GetCachedDataPoint(out url, out content);

                //wait for post response
                var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(content);
                CacheRequest        = UnityWebRequest.Put(url, bytes);
                CacheRequest.method = "POST";
                CacheRequest.SetRequestHeader("Content-Type", "application/json");
                CacheRequest.SetRequestHeader("X-HTTP-Method-Override", "POST");
                CacheRequest.SetRequestHeader("Authorization", CognitiveStatics.ApplicationKey);
                CacheRequest.Send();

                if (CognitiveVR_Preferences.Instance.EnableDevLogging)
                {
                    Util.logDevelopment("NETWORK LoopUploadFromLocalCache " + url + " " + content);
                }

                CacheResponseAction = Sender.CACHEDResponseCallback;

                Sender.StartCoroutine(Sender.WaitForFullResponse(CacheRequest, content, CacheResponseAction, false));
            }
            else if (lc.CacheEmpty())
            {
                if (cacheCompletedAction != null)
                {
                    cacheCompletedAction.Invoke();
                }
                cacheCompletedAction = null;
            }
        }
        private static void EnhanceSocketItem(IPlayerCharacterData character, CharacterItem enhancingItem, int enhancerId, System.Action <CharacterItem> onEnhanceSocket, out GameMessage.Type gameMessageType)
        {
            gameMessageType = GameMessage.Type.CannotEnhanceSocket;
            if (!enhancingItem.NotEmptySlot())
            {
                // Cannot enhance socket because character item is empty
                return;
            }
            Item equipmentItem = enhancingItem.GetEquipmentItem();

            if (equipmentItem == null)
            {
                // Cannot enhance socket because it's not equipment item
                return;
            }
            if (equipmentItem.maxSocket <= 0)
            {
                // Cannot enhance socket because equipment has no socket(s)
                return;
            }
            if (enhancingItem.Sockets.Count >= equipmentItem.maxSocket)
            {
                // Cannot enhance socket because socket is full
                return;
            }
            Item enhancerItem;

            if (!GameInstance.Items.TryGetValue(enhancerId, out enhancerItem) || !enhancerItem.IsSocketEnhancer())
            {
                // Cannot enhance socket because enhancer id is invalid
                return;
            }
            if (!character.DecreaseItems(enhancerItem.DataId, 1))
            {
                // Cannot enhance socket because there is no item
                gameMessageType = GameMessage.Type.NotEnoughSocketEnchaner;
                return;
            }
            enhancingItem.Sockets.Add(enhancerId);
            onEnhanceSocket.Invoke(enhancingItem);
        }
        private IEnumerator I_CheckInternet(System.Action <bool> res)
        {
            CheckRunning = true;
            Ping  ping = new Ping(PingIP);
            float t    = 0f;

            while (!ping.isDone)
            {
                t += Time.deltaTime;
                if (t >= Timeout)
                {
                    break;
                }

                yield return(new WaitForEndOfFrame());
            }

            bool response = ping.time > 0;

            if (res != null)
            {
                res.Invoke(response);
            }

            if (response)
            {
                OnInternet.Invoke();
            }
            else
            {
                OnNoInternet.Invoke();
            }

            LastResponse = response;

            ping.DestroyPing();

            CheckRunning = false;

            yield return(null);
        }
Exemple #15
0
    private IEnumerator IEMove(Vector2 pos, System.Action action = null)
    {
        bool isFlip = pos.x - transform.position.x < 0;//是否转向

        if (isFlip)
        {
            transform.localScale = new Vector2(-baseScale.x, baseScale.y);
        }
        else
        {
            transform.localScale = baseScale;
        }
        if (horizaltalMove)
        {
            pos = new Vector2(pos.x, transform.position.y);
        }
        while (Vector2.Distance(new Vector2(transform.position.x, transform.position.y), pos) >= disStop)
        {
            Vector2 dir = (pos - new Vector2(transform.position.x, transform.position.y));
            dir.Normalize();
            if (canMove)
            {
                if (horizaltalMove)
                {
                    dir = isFlip ? Vector2.left : Vector2.right;
                    transform.Translate(dir * Time.deltaTime * moveSpeed);
                }
                else
                {
                    transform.Translate(dir * Time.deltaTime * moveSpeed);
                }
            }
            yield return(null);
        }
        if (action != null)
        {
            action.Invoke();
        }
        _PlayerState  = PlayerState.Idle;
        moveCoroutine = null;
    }
Exemple #16
0
            public void UpdateTracker(Renderer[] Renderers, MaterialPropertyBlock[] Blocks, AniMeshData Data, int Index, float AnimatorSpeed)
            {
                // update frame
                _CurrentFrame = Mathf.Clamp(_CurrentFrame + ((_Clip.FrameRate * Time.deltaTime) * _Clip.Speed) * AnimatorSpeed, 0, _Clip.Length);
                if (_CurrentFrame >= _Clip.Length && _Clip.Loop)
                {
                    _CurrentFrame = 0;
                }

                // update strength
                Strength = Lerp(_From, _TargetStrength, FadePercentage());               // lerp to target strength

                // on done fading callback
                if (OnDoneFade != null && FadePercentage() >= 1f)
                {
                    OnDoneFade.Invoke();
                    OnDoneFade = null;
                }

                if (Strength <= 0 && !_Clip.Loop)
                {
                    ResetFrames();
                }

                // update renderers
                for (int i = 0; i < Blocks.Length; i++)
                {
                    if (Renderers [i].isVisible)
                    {
                        MaterialPropertyBlock props = Blocks [i];
                        Vector4 AnimationData       = new Vector4(
                            Lerp(ClipMin, ClipMax, (float)_CurrentFrame / (float)_Clip.Length),
                            Strength,
                            _Clip.MagnitudeMultiply,
                            0f
                            );
                        props.SetVector(_PropertyKeys [Index], AnimationData);
                        Renderers [i].SetPropertyBlock(props);
                    }
                }
            }
Exemple #17
0
        internal static IEnumerator CoAnimateToast(RectTransform toast, float target, System.Action cb = null)
        {
            var parent = toast.parent as RectTransform;
            var group  = toast.GetComponent <CanvasGroup>();
            var scale  = toast.localScale;

            float start   = scale.y;
            float delta   = Mathf.Abs(target - start);
            float elapsed = 0;

            while (elapsed <= delta)
            {
                elapsed += Time.deltaTime / AnimationTime;
                float t = Mathf.Lerp(start, target, elapsed);

                scale.y     = t;
                group.alpha = t;

                toast.localScale = scale;
                toast.ForceUpdateRectTransforms();

                LayoutRebuilder.MarkLayoutForRebuild(toast);

                yield return(null);

                if (!group)
                {
                    break;
                }
            }

            if (start != target)
            {
                singleton.UpdateVisibility(parent, target == 1 ? 1 : 0);
            }

            if (cb != null)
            {
                cb.Invoke();
            }
        }
Exemple #18
0
    public void CargarUrl(string url, System.Action alCompletar = null)
    {
        if (descargando)
        {
            Debug.LogError("ya estoy descargando");
        }
        if (string.IsNullOrEmpty(url))
        {
            Debug.LogError("string.IsNullOrEmpty(url)");
            return;
        }

        progresoDescarga = 0f;
        estadoDescarga   = "descargando...";
        descargando      = true;
        var uwr = new UnityEngine.Networking.UnityWebRequest(url, UnityEngine.Networking.UnityWebRequest.kHttpVerbGET);

        uwr.downloadHandler = new UnityEngine.Networking.DownloadHandlerTexture(true);
        EsperarUWR(uwr, () =>
        {
            descargando = false;
            if (uwr.downloadProgress == -1)
            {
                Debug.LogError("Descarga ni siquiera iniciada");
            }
            else if (uwr.isHttpError || uwr.isNetworkError)
            {
                Debug.LogError(uwr.error + "\nPedido (GET) " + uwr.url);
                estadoDescarga = uwr.error;
            }
            else
            {
                texturaDescargada = UnityEngine.Networking.DownloadHandlerTexture.GetContent(uwr);
                ActualizarTexturaOrigen(texturaDescargada);
                if (alCompletar != null)
                {
                    alCompletar.Invoke();
                }
            }
        });
    }
        public UdpServerSocket_Base(int Port, System.Action OnPacketReady, System.Action <int> OnListening, System.Action <string> OnCloseError, System.Action <float> OnKbpsReport)
        {
            if (OnKbpsReport == null)
            {
                OnKbpsReport = (Kbps) => Debug.Log("UDP Server Recieved " + Kbps + "kb/s");
            }

            //	todo: put some "unhandled" debug in these
            if (OnPacketReady == null)
            {
                OnPacketReady = () => { }
            }
            ;
            if (OnCloseError == null)
            {
                OnCloseError = (Error) => { }
            }
            ;
            if (OnListening == null)
            {
                OnListening = (Portx) => { }
            }
            ;

            RecvKbCounter = new FrameCounter(OnKbpsReport, 1.0f);

            this.OnPacketReady = OnPacketReady;
            this.OnCloseError  = OnCloseError;

            ListeningEndPoint = new IPEndPoint(IPAddress.Any, Port);
            Socket            = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Socket.Bind(ListeningEndPoint);
            var ReceiveBufferSize = Socket.ReceiveBufferSize;

            Debug.Log("Socket ReceiveBufferSize=" + ReceiveBufferSize);

            var LocalEndPoint = (IPEndPoint)Socket.LocalEndPoint;

            OnListening.Invoke(LocalEndPoint.Port);
            StartRecv();
        }
Exemple #20
0
        public static void RequestRankData(int type, System.Action callback)
        {
            int lastTime;

            if (ActivityRankDic.TryGetValue(type, out lastTime))
            {
                int nowTime = EB.Time.Now;
                if (nowTime - lastTime > 300)
                {
                    LTMainHudManager.Instance.UpdateActivityLoginData(callback);
                    ActivityRankDic[type] = nowTime;
                }
                else
                {
                    if (callback != null)
                    {
                        callback.Invoke();
                    }
                }
            }
        }
Exemple #21
0
    // Update is called once per frame
    void Update()
    {
        if (running)
        {
            cg.alpha = Mathf.Lerp(cg.alpha, 1.0f, 0.5f);
        }
        else
        {
            cg.alpha = Mathf.Lerp(cg.alpha, 0.0f, 0.5f);
        }

        if (Input.anyKeyDown)
        {
            running        = false;
            Time.timeScale = 1.0f;
            if (cb != null)
            {
                cb.Invoke();
            }
        }
    }
Exemple #22
0
 private IEnumerator Move(float t, bool offScreen, System.Action finishedAction = null)
 {
     for (float i = 0; i <= t; i += Time.deltaTime)
     {
         float dx = Curve.Evaluate(i / t) * widthRatio;
         if (!offScreen)
         {
             dx = widthRatio - dx;
         }
         rectTransform.anchoredPosition = new Vector3(dx, rectTransform.position.y, rectTransform.position.z);
         if (i + Time.deltaTime > t)
         {
             //Coroutine is finishing
             if (finishedAction != null)
             {
                 finishedAction.Invoke();
             }
         }
         yield return(null);
     }
 }
Exemple #23
0
        public virtual void OnDeinit(System.Action callback)
        {
            this.window = null;
            if (this.navigationGroup != null)
            {
                this.navigationGroup.Clear();
            }

            if (this != null && this.IsDestroyable() == true)
            {
                //WindowObject.Destroy(this);
                //WindowObject.Destroy(this.gameObject);
                //Debug.LogWarning("RECYCLE: " + this.name);
                this.Recycle();
            }

            WindowSystemResources.UnregisterObject(this);
            WindowSystem.RemoveDebugWeakReference(this);

            callback.Invoke();
        }
        static void InvokeAction <T>(IEnumerator <T> enumerator, System.Action <T> action, T item, object syncRoot, int i)
        {
            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name =
                    string.Format("Parallel.ForEach Worker Thread No:{0}", i);
            }

            bool moveNext = true;

            while (moveNext)
            {
                action.Invoke(item);

                lock (syncRoot)
                {
                    moveNext = enumerator.MoveNext();
                    item     = enumerator.Current;
                }
            }
        }
Exemple #25
0
    // Start is called before the first frame update
    void Start()
    {
        poolDictionnary = new Dictionary <string, Queue <GameObject> >();

        foreach (Pool pool in pools)
        {
            Queue <GameObject> objectPool = new Queue <GameObject>();
            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.prefab, transform);
                obj.SetActive(false);
                objectPool.Enqueue(obj);
            }
            poolDictionnary.Add(pool.tag, objectPool);
        }

        if (onPoolsCreated != null)
        {
            onPoolsCreated.Invoke();
        }
    }
Exemple #26
0
        IEnumerator RecognizeCoroutine(GestureData data, System.Action <RecognitionResult> callback, bool normalizeScale)
        {
            RecognitionResult result = null;

            //runs recocnition in another thread to avoid framerate drop

            var thread = new System.Threading.Thread(() => {
                var normData = NormalizeData(data, normalizeScale);
                var found    = findPattern(normData, normalizeScale);
                result       = found;
            });

            thread.Start();

            while (thread.IsAlive)
            {
                yield return(null);
            }

            callback.Invoke(result);
        }
Exemple #27
0
        private void OnItemCallback_INTERNAL <T>(Item item, ResourceBase resource, System.Action <T> callbackLoaded, System.Action callbackFailed) /*where T : Object*/
        {
            item.onObjectLoaded += (itemInner) => {
                if (WindowSystemResources.RemoveIfRefsZero_INTERNAL(itemInner, resource) == true)
                {
                    return;
                }

                if (callbackLoaded != null)
                {
                    callbackLoaded.Invoke((T)itemInner.loadedObject);
                }
            };

            item.onObjectFailed += (itemInner) => {
                if (callbackFailed != null)
                {
                    callbackFailed.Invoke();
                }
            };
        }
        private IEnumerator MoveToTargetInternal(Transform transform, Vector3 position, Quaternion rotation, float time, System.Action onComplete)
        {
            this.m_InPosition = false;
            float      elapsedTime      = 0f;
            Vector3    startingPosition = transform.position;
            Quaternion startingRotation = transform.rotation;

            while (elapsedTime < time)
            {
                transform.position = Vector3.Lerp(startingPosition, position, (elapsedTime / time));
                transform.rotation = Quaternion.Slerp(startingRotation, rotation, (elapsedTime / time));
                elapsedTime       += Time.deltaTime;
                yield return(new WaitForEndOfFrame());
            }
            this.m_InPosition = true;

            if (onComplete != null)
            {
                onComplete.Invoke();
            }
        }
Exemple #29
0
        static StackObject *Invoke_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Int32 @arg2 = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            ILRuntime.Runtime.Intepreter.ILTypeInstance @arg1 = (ILRuntime.Runtime.Intepreter.ILTypeInstance) typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Action <ILRuntime.Runtime.Intepreter.ILTypeInstance, System.Int32> instance_of_this_method = (System.Action <ILRuntime.Runtime.Intepreter.ILTypeInstance, System.Int32>) typeof(System.Action <ILRuntime.Runtime.Intepreter.ILTypeInstance, System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Invoke(@arg1, @arg2);

            return(__ret);
        }
Exemple #30
0
    private void Transit(TransitionType transitionType, System.Action callback = null, bool finish = true)
    {
        bool exit = transitionType == TransitionType.Exit;

        Color colorBegin = background.color;

        colorBegin.a     = exit ? 1 : 0;
        background.color = colorBegin;

        background.DOFade(exit ? 0 : 1, fadeDuration).SetEase(Ease.InOutQuad).OnComplete(() => {
            if (callback != null)
            {
                callback.Invoke();
            }
            if (finish)
            {
                transitionRunning = false;
                gameObject.SetActive(false);
            }
        });
    }