Improved code

mail@pastecode.io avatar
unknown
csharp
2 years ago
2.4 kB
62
Indexable
Never
    /// <summary>
    /// Refreshes the position and size of the nicknames on the UI
    /// </summary>
    public void RefreshUI()
    {
        // Caching
        _camPos = CameraGO.instance.transform.position;
        _camForward = CameraGO.instance.transform.forward;

        for (int i = 0; i < GameGO.instance.controllerGOs.Count; i++)
        {
            // Caching
            _cachedCtrlrGO = GameGO.instance.controllerGOs[i];

            // UI player representation shouldn't be visible at all
            if (_cachedCtrlrGO.team == LocalClient.team || _cachedCtrlrGO.gameObject.activeSelf || _cachedCtrlrGO == CameraGO.instance.targetGO)
            {
                HideBothUIElements();
                continue;
            }

            // Player nickname is not in the camera's FoV
            if (Vector3.Dot((_cachedCtrlrGO.nicknameHolder.position - _camPos).normalized, _camForward) <= 0)
            {
                HideBothUIElements();
                continue;
            }

            // Determinating which UI element is used to represent the player (Either full text nickname or simple colored dot)
            if (_cachedCtrlrGO.distToCam > FULL_NICKNAME_VISIBILITY_DISTANCE)
            {
                _activeUIelement = _cachedCtrlrGO.nickname_image.gameObject;
                otherUIelement = _cachedCtrlrGO.nicknameUI_text.gameObject;
            }
            else
            {
                _activeUIelement = _cachedCtrlrGO.nicknameUI_text.gameObject;
                otherUIelement = _cachedCtrlrGO.nickname_image.gameObject;
            }

            // Updating the UI element position
            _activeUIelement.transform.position = Vector2.Lerp(_activeUIelement.transform.position, _cam.WorldToScreenPoint(_cachedCtrlrGO.nicknameHolder.position), 100);

            // Enabling the active UI element, disabling the other
            if (!_activeUIelement.activeSelf) _activeUIelement.SetActive(true);
            if (otherUIelement.activeSelf) otherUIelement.SetActive(false);
        }
    }

    void HideBothUIElements()
    {
        // Hiding all UI elements if they were being shown
        if (_cachedCtrlrGO.nickname_image.gameObject.activeSelf) _cachedCtrlrGO.nickname_image.gameObject.SetActive(false);
        if (_cachedCtrlrGO.nicknameUI_text.gameObject.activeSelf) _cachedCtrlrGO.nicknameUI_text.gameObject.SetActive(false);
    }