void Start () { mTrans = transform; mUITex = GetComponent<UITexture>(); mCam = UICamera.FindCameraForLayer(gameObject.layer); mWidth = mUITex.width; mHeight = mUITex.height; Color[] cols = new Color[mWidth * mHeight]; for (int y = 0; y < mHeight; ++y) { float fy = (y - 1f) / mHeight; for (int x = 0; x < mWidth; ++x) { float fx = (x - 1f) / mWidth; int index = x + y * mWidth; cols[index] = Sample(fx, fy); } } mTex = new Texture2D(mWidth, mHeight, TextureFormat.RGB24, false); mTex.SetPixels(cols); mTex.filterMode = FilterMode.Trilinear; mTex.wrapMode = TextureWrapMode.Clamp; mTex.Apply(); mUITex.mainTexture = mTex; Select(value); }
/// <summary> /// Init all roots and configs /// </summary> void InitFuc() { Application.runInBackground = playInBackGround; Debuger.EnableLog = enableDebuger; manager = this.gameObject.AddComponent<SceneManager>(); manager.cacheRoot = transform.FindChild("CacheRoot"); manager.uiRoot = transform.FindChild("UI Root"); manager.senceRoot = transform.FindChild("SceneRoot"); manager.playerRoot = transform.FindChild("PlayerRoot"); manager.ghostRoot = transform.FindChild("GhostRoot"); uicamera = manager.uiRoot.FindChild("Camera").GetComponent<UICamera>(); tool = this.gameObject.AddComponent<Utility>(); connector = this.gameObject.AddComponent<Connector>(); this.gameObject.AddComponent<CacheFactory>(); ConfigFactory.InitResourceConfig(); ConfigFactory.ReadSystemConfig(); this.gameObject.AddComponent<ConfigInfo>(); ConfigInfo.ReadUIRules(); GUIManager.instance.Loading.gameObject.SetActive(true); GUIManager.instance.FloatMessagePanel.gameObject.SetActive(true); GUIManager.instance.FloatTip.gameObject.SetActive(true); GUIManager.LoadingPercent(10); ConfigInfo.Init(); ConfigInfo.InitPreGameConfigs(); GUIManager.FinishLoading(); StartGame(); }
void Awake() { m_myTransform = transform; FillFullNameData(m_myTransform); m_instance = m_myTransform.GetComponentsInChildren<InstanceMissionChooseUIViewManager>(true)[0]; m_lblSweepNum = m_myTransform.FindChild(m_widgetToFullName["InstanceLeftChallengeNum"]).GetComponentsInChildren<UILabel>(true)[0]; m_lblResetNum = m_myTransform.FindChild(m_widgetToFullName["InstanceLeftResetNum"]).GetComponentsInChildren<UILabel>(true)[0]; m_camInstanceMissionChooseUI = FindTransform("InstanceMissionChooseUICamera").GetComponentsInChildren<Camera>(true)[0]; m_uicamInstanceMissionChooseUI = m_myTransform.FindChild(m_widgetToFullName["InstanceMissionChooseUICamera"]).GetComponentsInChildren<UICamera>(true)[0]; m_goInstanceMissionChooseUIMapListGrid = m_myTransform.FindChild(m_widgetToFullName["InstanceMissionChooseUIMapListGrid"]).gameObject; m_tranInstanceMissionChooseUIPageDOT = FindTransform("InstanceMissionChooseUIPageDOT"); m_goGOInstanceMissionChooseUI = m_myTransform.FindChild(m_widgetToFullName["GOInstanceMissionChooseUI"]).gameObject; m_goGOInstanceMissionChooseUI.SetActive(false); m_goGOInstanceMissionChooseUIMapList = FindTransform("GOInstanceMissionChooseUIMapList").gameObject; m_goGOInstanceMissionChooseUINormal = FindTransform("GOInstanceMissionChooseUINormal").gameObject; m_goGOInstanceMissionChooseUIRandom = FindTransform("GOInstanceMissionChooseUIRandom").gameObject; m_chooseMogoSingleButtonList = FindTransform("InstanceMissionChooseUIChoose").GetComponentsInChildren<MogoSingleButtonList>(true)[0]; m_chooseMogoSingleButtonList.SetCurrentDownButton(0); m_lblInstanceMissionChooseUIChooseNormalText = FindTransform("InstanceMissionChooseUIChooseNormalText").GetComponentsInChildren<UILabel>(true)[0]; m_lblInstanceMissionChooseUIChooseNormalTextDown = FindTransform("InstanceMissionChooseUIChooseNormalTextDown").GetComponentsInChildren<UILabel>(true)[0]; m_lblInstanceMissionChooseUIChooseRandomText = FindTransform("InstanceMissionChooseUIChooseRandomText").GetComponentsInChildren<UILabel>(true)[0]; m_lblInstanceMissionChooseUIChooseRandomTextDown = FindTransform("InstanceMissionChooseUIChooseRandomTextDown").GetComponentsInChildren<UILabel>(true)[0]; m_lblInstanceMissionChooseUIRandomBtnEnterTip = FindTransform("InstanceMissionChooseUIRandomBtnEnterTip").GetComponentsInChildren<UILabel>(true)[0]; m_spInstanceMissionChooseUIChooseRandomBGUp = FindTransform("InstanceMissionChooseUIChooseRandomBGUp").GetComponentsInChildren<UISprite>(true)[0]; m_spInstanceMissionChooseUIChooseRandomBGDown = FindTransform("InstanceMissionChooseUIChooseRandomBGDown").GetComponentsInChildren<UISprite>(true)[0]; m_dragCamera = m_myTransform.FindChild(m_widgetToFullName["InstanceMissionChooseUIMapListCamera"]).GetComponentsInChildren<Camera>(true)[0]; Camera SourceCamera = GameObject.Find("MogoMainUI").transform.FindChild("Camera").GetComponentsInChildren<Camera>(true)[0]; m_dragCamera.GetComponentsInChildren<UIViewport>(true)[0].sourceCamera = SourceCamera; m_dragableCameraMapList = m_dragCamera.transform.GetComponentsInChildren<MyDragableCamera>(true)[0]; m_dragableCameraMapList.LeftArrow = FindTransform("InstanceMissionChooseUIArrowL").gameObject; m_dragableCameraMapList.RightArrow = FindTransform("InstanceMissionChooseUIArrowR").gameObject; FillNewInstanceUIChooseGridData(); // 随机副本特效 m_goInstanceMissionChooseUIRandomFx = FindTransform("InstanceMissionChooseUIRandomFx").gameObject; // ChineseData m_lblInstanceMissionChooseUIChooseRandomText.text = LanguageData.GetContent(46975); m_lblInstanceMissionChooseUIChooseRandomTextDown.text = LanguageData.GetContent(46975); m_lblInstanceMissionChooseUIRandomBtnEnterTip.text = LanguageData.GetContent(46976); Initialize(); }
void Start() { uiCamera = GameObject.FindObjectOfType(typeof(UICamera)) as UICamera; // Disable standard NGUI inputs uiCamera.useMouse = false; uiCamera.useTouch = false; TouchManager.Instance.TouchesBegan += TouchManagerBegan; TouchManager.Instance.TouchesMoved += TouchManagerMoved; TouchManager.Instance.TouchesEnded += TouchManagerEnded; TouchManager.Instance.TouchesCancelled += TouchManagerCancelled; }
private static void PreCreate () { if (m_uiRoot == null) { int uiLayer = LayerMask.NameToLayer("UI"); m_uiRootObj = new GameObject("UI Root(2D)"); m_uiRootObj.layer = uiLayer; UIRoot uiRoot = m_uiRootObj.AddComponent<UIRoot>(); { uiRoot.scalingStyle = UIRoot.Scaling.FixedSize; if ((Double)Screen.width / Screen.height < 1.49) uiRoot.manualHeight = 768; else uiRoot.manualHeight = 640; } m_cameraObj = new GameObject("Camera"); m_cameraObj.transform.parent = m_uiRootObj.transform; m_camera = m_cameraObj.AddComponent<Camera>(); { float depth = -1f; m_camera.gameObject.layer = uiLayer; m_camera.depth = depth + 1; m_camera.backgroundColor = Color.black; m_camera.cullingMask = 1 << uiLayer; //Use Simple2D Camera m_camera.orthographicSize = 1f; m_camera.orthographic = true; m_camera.nearClipPlane = -2f; m_camera.farClipPlane = 2f; m_camera.gameObject.AddComponent<UICamera>(); //m_camera.gameObject.AddComponent<UITick>(); } m_uiCamera = m_cameraObj.AddComponent<UICamera>(); m_uiRootObj.AddComponent<UIPanel>(); m_uiRoot = uiRoot; } }
public override void Start() { base.Start(); _nguiCamera = NguiUtils.GetComponentInParents<UICamera>(gameObject); var anchor = NguiUtils.GetComponentInParents<UIAnchor>(gameObject); if (anchor == null) { Debug.LogWarning("There have to be an UIAnchor upper in the hierarchy"); return; } if (anchor.side != UIAnchor.Side.BottomLeft && anchor.side != UIAnchor.Side.BottomRight && anchor.side != UIAnchor.Side.TopLeft && anchor.side != UIAnchor.Side.TopRight) { Debug.LogWarning("Parent UIAnchor have to be a corner one (BottomLeft, BottomRight, TopLeft or TopRight)"); } _anchor = anchor.transform; }
void CreateUIRoot() { GameObject uiRootobj = new GameObject("UIRoot"); UiRoot = uiRootobj.AddComponent<UIRoot>(); CBase.Assert(UiRoot); UiRoot.scalingStyle = UIRoot.Scaling.ConstrainedOnMobiles; UiRoot.manualHeight = 1920; GameObject panelRootObj = new GameObject("PanelRoot"); CTool.SetChild(panelRootObj.transform, uiRootobj.transform); Transform panelTrans = panelRootObj.transform; PanelRoot = panelRootObj.AddComponent<UIPanel>(); CBase.Assert(PanelRoot); GameObject uiCamObj = new GameObject("UICamera"); CTool.SetChild(uiCamObj.transform, UiRoot.transform); UiCamera = uiCamObj.AddComponent<UICamera>(); UiCamera.cachedCamera.cullingMask = 1 << (int)CLayerDef.UI; UiCamera.cachedCamera.clearFlags = CameraClearFlags.Depth; UiCamera.cachedCamera.orthographic = true; UiCamera.cachedCamera.orthographicSize = 1; UiCamera.cachedCamera.nearClipPlane = -2; UiCamera.cachedCamera.farClipPlane = 2; //panelTrans.gameObject.isStatic = true; foreach (UIAnchor.Side side in Enum.GetValues(typeof(UIAnchor.Side))) { GameObject anchorObj = new GameObject(side.ToString()); CTool.SetChild(anchorObj.transform, panelTrans); AnchorSide[side.ToString()] = anchorObj.transform; } GameObject nullAnchor = new GameObject("Null"); CTool.SetChild(nullAnchor.transform, panelTrans); AnchorSide["Null"] = nullAnchor.transform; AnchorSide[""] = AnchorSide[UIAnchor.Side.Center.ToString()]; // default NGUITools.SetLayer(uiRootobj, (int)CLayerDef.UI); }
void Awake() { Instance = this; currentMenu = MenuType.Main; Transform UIRoot = transform.FindChild("UI Root"); MainCamera = UIRoot.FindChild("Camera").GetComponent<UICamera>(); MainCamera.enabled = true; MainCamera.GetComponent<Camera>().enabled = true; // Get transforms for each menu MainMenu = UIRoot.FindChild("Main Menu"); SettingsMenu = UIRoot.FindChild("Settings Menu"); LeaderboardMenu = UIRoot.FindChild("Leaderboard Menu"); GameMenu = UIRoot.FindChild("Game Menu"); CustomizeMenu = UIRoot.FindChild("Customize Menu"); ToggleMenusOn(); }
void OnEnable() { Time.timeScale = PAUSED_TIME_SCALE; GameObject uiRoot = GameObject.Find("UI Root"); if(uiRoot!=null) { UICamera camera = uiRoot.GetComponentInChildren<UICamera>(); if(camera!=null) { camera.eventType = UICamera.EventType.UI_3D; cameraRef = camera; if(Application.loadedLevelName=="Garage") { blur = camera.GetComponent<CC_RadialBlur>(); if(blur==null) { blur = camera.gameObject.AddComponent<CC_RadialBlur>(); } blur.enabled = true; /* analogTV = camera.GetComponent<CC_AnalogTV>(); if(analogTV==null) { analogTV = camera.gameObject.AddComponent<CC_AnalogTV>(); }*/ //analogTV.enabled = true; } } } }
private void OnDestroy() { mainCamera = null; uiCamera = null; playerDeathCountLabel = null; enemyDeathCountLabel = null; player = null; if (enemyList != null) { enemyList.Clear(); enemyList = null; } if (enemySummonZoneList != null) { enemySummonZoneList.Clear(); enemySummonZoneList = null; } tileArray = null; fileManager = null; flag = null; }
void Awake() { uiCamera = GetComponent<UICamera>(); }
private static bool IsVisible(ref UICamera.DepthEntry de) { UIPanel uIPanel = NGUITools.FindInParents<UIPanel>(de.go); while (uIPanel != null) { if (!uIPanel.IsVisible(de.point)) { return false; } uIPanel = uIPanel.parentPanel; } return true; }
/// <summary> /// Returns the object under the specified position. /// </summary> static public bool Raycast(Vector3 inPos, out RaycastHit hit) { for (int i = 0; i < mList.Count; ++i) { UICamera cam = mList[i]; // Skip inactive scripts if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) { continue; } // Convert to view space currentCamera = cam.cachedCamera; Vector3 pos = currentCamera.ScreenToViewportPoint(inPos); if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) { continue; } // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) { continue; } // Cast a ray into the screen Ray ray = currentCamera.ScreenPointToRay(inPos); // Raycast into the screen int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask; float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane; // If raycasts should be clipped by panels, we need to find a panel for each hit if (cam.clipRaycasts) { RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask); if (hits.Length > 1) { System.Array.Sort(hits, delegate(RaycastHit r1, RaycastHit r2) { return(r1.distance.CompareTo(r2.distance)); }); for (int b = 0, bmax = hits.Length; b < bmax; ++b) { if (IsVisible(ref hits[b])) { hit = hits[b]; return(true); } } } else if (hits.Length == 1 && IsVisible(ref hits[0])) { hit = hits[0]; return(true); } continue; } if (Physics.Raycast(ray, out hit, dist, mask)) { return(true); } } hit = mEmpty; return(false); }
void OnGUI() { Rect rect = new Rect(5f, 5f, 1000f, 22f); if (mRayDebug) { UICamera.ControlScheme scheme = UICamera.currentScheme; string text = "Scheme: " + scheme; GUI.color = Color.black; GUI.Label(rect, text); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, text); rect.y += 18f; rect.x += 1f; text = "Hover: " + NGUITools.GetHierarchy(UICamera.hoveredObject).Replace("\"", ""); GUI.color = Color.black; GUI.Label(rect, text); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, text); rect.y += 18f; rect.x += 1f; text = "Selection: " + NGUITools.GetHierarchy(UICamera.selectedObject).Replace("\"", ""); GUI.color = Color.black; GUI.Label(rect, text); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, text); rect.y += 18f; rect.x += 1f; text = "Controller: " + NGUITools.GetHierarchy(UICamera.controllerNavigationObject).Replace("\"", ""); GUI.color = Color.black; GUI.Label(rect, text); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, text); rect.y += 18f; rect.x += 1f; text = "Active events: " + UICamera.CountInputSources(); if (UICamera.disableController) { text += ", disabled controller"; } if (UICamera.ignoreControllerInput) { text += ", ignore controller"; } if (UICamera.inputHasFocus) { text += ", input focus"; } GUI.color = Color.black; GUI.Label(rect, text); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, text); rect.y += 18f; rect.x += 1f; } for (int i = 0, imax = mLines.Count; i < imax; ++i) { GUI.color = Color.black; GUI.Label(rect, mLines[i]); rect.y -= 1f; rect.x -= 1f; GUI.color = Color.white; GUI.Label(rect, mLines[i]); rect.y += 18f; rect.x += 1f; } }
private void OnPress(bool isPressed) { if (base.enabled) { if (!this.mStarted) { this.Start(); } TweenRotation.Begin(this.tweenTarget.gameObject, this.duration, (!isPressed) ? ((!UICamera.IsHighlighted(base.gameObject)) ? this.mRot : (this.mRot * Quaternion.Euler(this.hover))) : (this.mRot * Quaternion.Euler(this.pressed))).method = UITweener.Method.EaseInOut; } }
protected virtual void OnBindingClick() { UICamera.Notify(base.gameObject, "OnClick", null); }
/// <summary> /// Returns the object under the specified position. /// </summary> static public bool Raycast(Vector3 inPos, out RaycastHit hit) { for (int i = 0; i < list.Count; ++i) { UICamera cam = list[i]; // Skip inactive scripts if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) { continue; } // Convert to view space currentCamera = cam.cachedCamera; Vector3 pos = currentCamera.ScreenToViewportPoint(inPos); if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) { continue; } // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) { continue; } // Cast a ray into the screen Ray ray = currentCamera.ScreenPointToRay(inPos); // Raycast into the screen int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask; float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane; if (cam.eventType == EventType.World) { if (Physics.Raycast(ray, out hit, dist, mask)) { hoveredObject = hit.collider.gameObject; return(true); } continue; } else if (cam.eventType == EventType.UI) { RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask); if (hits.Length > 1) { for (int b = 0; b < hits.Length; ++b) { GameObject go = hits[b].collider.gameObject; mHit.depth = NGUITools.CalculateRaycastDepth(go); if (mHit.depth != int.MaxValue) { mHit.hit = hits[b]; mHits.Add(mHit); } } mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return(r2.depth.CompareTo(r1.depth)); }); for (int b = 0; b < mHits.size; ++b) { #if UNITY_FLASH if (IsVisible(mHits.buffer[b])) #else if (IsVisible(ref mHits.buffer[b])) #endif { hit = mHits[b].hit; hoveredObject = hit.collider.gameObject; mHits.Clear(); return(true); } } mHits.Clear(); } else if (hits.Length == 1 && IsVisible(ref hits[0])) { hit = hits[0]; hoveredObject = hit.collider.gameObject; return(true); } continue; } } hit = mEmpty; return(false); }
/// <summary> /// Helper function used to print things in columns. /// </summary> void DrawRow(Camera cam) { bool highlight = (cam == null || Selection.activeGameObject == null) ? false : (0 != (cam.cullingMask & (1 << Selection.activeGameObject.layer))); if (cam != null) { GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f); GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f)); GUI.backgroundColor = Color.white; } else { GUILayout.BeginHorizontal(); } bool enabled = (cam == null || (NGUITools.GetActive(cam.gameObject) && cam.enabled)); GUI.color = Color.white; if (cam != null) { if (enabled != EditorGUILayout.Toggle(enabled, GUILayout.Width(20f))) { cam.enabled = !enabled; EditorUtility.SetDirty(cam.gameObject); } } else { GUILayout.Space(30f); } if (enabled) { GUI.color = highlight ? new Color(0f, 0.8f, 1f) : Color.white; } else { GUI.color = highlight ? new Color(0f, 0.5f, 0.8f) : Color.grey; } string camName, camLayer; if (cam == null) { camName = "Camera's Name"; camLayer = "Layer"; } else { camName = cam.name + (cam.orthographic ? " (2D)" : " (3D)"); camLayer = LayerMask.LayerToName(cam.gameObject.layer); } if (GUILayout.Button(camName, EditorStyles.label, GUILayout.MinWidth(100f)) && cam != null) { Selection.activeGameObject = cam.gameObject; EditorUtility.SetDirty(cam.gameObject); } GUILayout.Label(camLayer, GUILayout.Width(70f)); GUI.color = enabled ? Color.white : new Color(0.7f, 0.7f, 0.7f); if (cam == null) { GUILayout.Label("EV", GUILayout.Width(26f)); } else { UICamera uic = cam.GetComponent <UICamera>(); bool ev = (uic != null && uic.enabled); if (ev != EditorGUILayout.Toggle(ev, GUILayout.Width(20f))) { if (uic == null) { uic = cam.gameObject.AddComponent <UICamera>(); } uic.enabled = !ev; } } if (cam == null) { GUILayout.Label("Mask", GUILayout.Width(100f)); } else { int mask = LayerMaskField(cam.cullingMask, GUILayout.Width(105f)); if (cam.cullingMask != mask) { NGUIEditorTools.RegisterUndo("Camera Mask Change", cam); cam.cullingMask = mask; } } GUILayout.EndHorizontal(); }
static public void ClearColor(bool clear) { UICamera camera = uiRoot.GetComponentInChildren <UICamera>(); camera.camera.clearFlags = CameraClearFlags.Depth; }
public override void Show() { if (base.enabled && NGUITools.GetActive(base.gameObject) && UIPopupList.mChild == null && this.atlas != null && this.isValid && this.items.Count > 0) { this.mLabelList.Clear(); base.StopCoroutine("CloseIfUnselected"); UICamera.selectedObject = (UICamera.hoveredObject ?? base.gameObject); this.mSelection = UICamera.selectedObject; this.source = UICamera.selectedObject; if (this.source == null) { Debug.LogError("Popup list needs a source object..."); return; } this.mOpenFrame = Time.frameCount; if (this.mPanel == null) { this.mPanel = UIPanel.Find(base.transform); if (this.mPanel == null) { return; } } UIPopupList.mChild = new GameObject("Drop-down List"); UIPopupList.mChild.layer = base.gameObject.layer; UIPopupList.current = this; Transform transform = UIPopupList.mChild.transform; transform.parent = this.mPanel.cachedTransform; Vector3 vector; Vector3 vector2; Vector3 vector3; if (this.openOn == UIPopupList.OpenOn.Manual && this.mSelection != base.gameObject) { vector = UICamera.lastEventPosition; vector2 = this.mPanel.cachedTransform.InverseTransformPoint(this.mPanel.anchorCamera.ScreenToWorldPoint(vector)); vector3 = vector2; transform.localPosition = vector2; vector = transform.position; } else { Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(this.mPanel.cachedTransform, base.transform, false, false); vector2 = bounds.min; vector3 = bounds.max; transform.localPosition = vector2; vector = transform.position; } base.StartCoroutine("CloseIfUnselected"); transform.localRotation = Quaternion.identity; transform.localScale = Vector3.one; this.mBackground = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.backgroundSprite); this.mBackground.pivot = UIWidget.Pivot.TopLeft; this.mBackground.depth = NGUITools.CalculateNextDepth(this.mPanel.gameObject); this.mBackground.color = this.backgroundColor; Vector4 border = this.mBackground.border; this.mBgBorder = border.y; this.mBackground.cachedTransform.localPosition = new Vector3(0f, border.y, 0f); this.mHighlight = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.highlightSprite); this.mHighlight.pivot = UIWidget.Pivot.TopLeft; this.mHighlight.color = this.highlightColor; UISpriteData atlasSprite = this.mHighlight.GetAtlasSprite(); if (atlasSprite == null) { return; } float num = (float)atlasSprite.borderTop; float num2 = (float)this.activeFontSize; float activeFontScale = this.activeFontScale; float num3 = num2 * activeFontScale; float num4 = 0f; float num5 = -this.padding.y; List <UILabel> list = new List <UILabel>(); List <UITexture> list2 = new List <UITexture>(); if (!this.items.Contains(this.mSelectedItem)) { this.mSelectedItem = null; } int i = 0; int count = this.items.Count; while (i < count) { string text = this.items[i]; Texture texture = this.itemsIcon[i]; UILabel uilabel = NGUITools.AddWidget <UILabel>(UIPopupList.mChild); uilabel.name = i.ToString(); uilabel.pivot = UIWidget.Pivot.TopLeft; uilabel.bitmapFont = this.bitmapFont; uilabel.trueTypeFont = this.trueTypeFont; uilabel.fontSize = this.fontSize; uilabel.fontStyle = this.fontStyle; string text2 = (!this.isLocalized) ? text : Localization.Get(text); if (this.toUpper) { text2 = text2.ToUpper(); } uilabel.text = text2; uilabel.color = this.textColor; uilabel.cachedTransform.localPosition = new Vector3(border.x + this.padding.x - uilabel.pivotOffset.x + this.iconWidth, num5, -1f); uilabel.overflowMethod = UILabel.Overflow.ResizeFreely; uilabel.alignment = this.alignment; list.Add(uilabel); if (texture) { UITexture uitexture = NGUITools.AddWidget <UITexture>(uilabel.gameObject); uitexture.name = i.ToString(); uitexture.pivot = UIWidget.Pivot.TopLeft; uitexture.width = 28; uitexture.height = 18; uitexture.mainTexture = texture; uitexture.cachedTransform.localPosition = new Vector3(-this.iconWidth, 0f, -1f); list2.Add(uitexture); } else { list2.Add(null); } num5 -= num3; num5 -= this.padding.y; num4 = Mathf.Max(num4, uilabel.printedSize.x); UIEventListener uieventListener = UIEventListener.Get(uilabel.gameObject); uieventListener.onHover = new UIEventListener.BoolDelegate(base.OnItemHover); uieventListener.onPress = new UIEventListener.BoolDelegate(base.OnItemPress); uieventListener.parameter = text; if (this.mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(this.mSelectedItem))) { base.Highlight(uilabel, true); } this.mLabelList.Add(uilabel); i++; } num4 = Mathf.Max(num4 + this.iconWidth, vector3.x - vector2.x - (border.x + this.padding.x) * 2f); float num6 = num4; Vector3 vector4 = new Vector3(num6 * 0.5f, -num3 * 0.5f, 0f); Vector3 vector5 = new Vector3(num6, num3 + this.padding.y, 1f); int j = 0; int count2 = list.Count; while (j < count2) { UILabel uilabel2 = list[j]; NGUITools.AddWidgetCollider(uilabel2.gameObject); uilabel2.autoResizeBoxCollider = false; BoxCollider component = uilabel2.GetComponent <BoxCollider>(); if (component != null) { vector4.z = component.center.z; component.center = vector4; component.size = vector5; } else { BoxCollider2D component2 = uilabel2.GetComponent <BoxCollider2D>(); component2.offset = vector4; component2.size = vector5; } j++; } int width = Mathf.RoundToInt(num4); num4 += (border.x + this.padding.x) * 2f; num5 -= border.y; this.mBackground.width = Mathf.RoundToInt(num4); this.mBackground.height = Mathf.RoundToInt(-num5 + border.y); int k = 0; int count3 = list.Count; while (k < count3) { UILabel uilabel3 = list[k]; uilabel3.overflowMethod = UILabel.Overflow.ShrinkContent; uilabel3.width = width; k++; } float num7 = 2f * this.atlas.pixelSize; float f = num4 - (border.x + this.padding.x) * 2f + (float)atlasSprite.borderLeft * num7; float f2 = num3 + num * num7; this.mHighlight.width = Mathf.RoundToInt(f); this.mHighlight.height = Mathf.RoundToInt(f2); bool flag = this.position == UIPopupList.Position.Above; UICamera uicamera = UICamera.FindCameraForLayer(this.mSelection.layer); if (this.position == UIPopupList.Position.Auto && uicamera != null) { flag = (uicamera.cachedCamera.WorldToViewportPoint(vector).y < 0.5f); } if (this.isAnimated) { base.AnimateColor(this.mBackground); if (Time.timeScale == 0f || Time.timeScale >= 0.1f) { float bottom = num5 + num3; base.Animate(this.mHighlight, flag, bottom); int l = 0; int count4 = list.Count; while (l < count4) { base.Animate(list[l], flag, bottom); l++; } base.AnimateScale(this.mBackground, flag, bottom); } } if (flag) { vector2.y = vector3.y - border.y; vector3.y = vector2.y + (float)this.mBackground.height; vector3.x = vector2.x + (float)this.mBackground.width; transform.localPosition = new Vector3(vector2.x, vector3.y - border.y, vector2.z); } else { vector3.y = vector2.y + border.y; vector2.y = vector3.y - (float)this.mBackground.height; vector3.x = vector2.x + (float)this.mBackground.width; } Transform parent = this.mPanel.cachedTransform.parent; if (parent != null) { vector2 = this.mPanel.cachedTransform.TransformPoint(vector2); vector3 = this.mPanel.cachedTransform.TransformPoint(vector3); vector2 = parent.InverseTransformPoint(vector2); vector3 = parent.InverseTransformPoint(vector3); } if (uicamera != null) { transform.position = base.transform.TransformPoint(new Vector3((float)(-(float)this.mBackground.width) + this.iconWidth / 2f, (float)(((!flag) ? -1 : 1) * (this.mBackground.height + 10)), 0f)); } else { Vector3 b = (!this.mPanel.hasClipping) ? this.mPanel.CalculateConstrainOffset(vector2, vector3) : Vector3.zero; vector = transform.localPosition + b; vector.x = Mathf.Round(vector.x); vector.y = Mathf.Round(vector.y); transform.localPosition = vector; } } else { base.OnSelect(false); } }
private void OnPress(bool isPressed) { if (base.enabled) { if (!this.mStarted) { this.Start(); } TweenScale.Begin(this.tweenTarget.gameObject, this.duration, (!isPressed) ? ((!UICamera.IsHighlighted(base.gameObject)) ? this.mScale : Vector3.Scale(this.mScale, this.hover)) : Vector3.Scale(this.mScale, this.pressed)).method = UITweener.Method.EaseInOut; } }
/// <summary> /// Wrap all content, repositioning all children as needed. /// </summary> public void WrapContent() { float extents = itemSize * mChildren.Count * 0.5f; Vector3[] corners = mPanel.worldCorners; for (int i = 0; i < 4; ++i) { Vector3 v = corners[i]; v = mTrans.InverseTransformPoint(v); corners[i] = v; } Vector3 center = Vector3.Lerp(corners[0], corners[2], 0.5f); bool allWithinRange = true; float ext2 = extents * 2f; if (mHorizontal) { float min = corners[0].x - itemSize; float max = corners[2].x + itemSize; for (int i = 0, imax = mChildren.Count; i < imax; ++i) { Transform t = mChildren[i]; float distance = t.localPosition.x - center.x; if (distance < -extents) { Vector3 pos = t.localPosition; pos.x += ext2; distance = pos.x - center.x; int realIndex = Mathf.RoundToInt(pos.x / itemSize); if (minIndex == maxIndex || (minIndex <= realIndex && realIndex <= maxIndex)) { t.localPosition = pos; UpdateItem(t, i); } else { allWithinRange = false; } } else if (distance > extents) { Vector3 pos = t.localPosition; pos.x -= ext2; distance = pos.x - center.x; int realIndex = Mathf.RoundToInt(pos.x / itemSize); if (minIndex == maxIndex || (minIndex <= realIndex && realIndex <= maxIndex)) { t.localPosition = pos; UpdateItem(t, i); } else { allWithinRange = false; } } else if (mFirstTime) { UpdateItem(t, i); } if (cullContent) { distance += mPanel.clipOffset.x - mTrans.localPosition.x; if (!UICamera.IsPressed(t.gameObject)) { NGUITools.SetActive(t.gameObject, (distance > min && distance < max), false); } } } } else { float min = corners[0].y - itemSize; float max = corners[2].y + itemSize; for (int i = 0, imax = mChildren.Count; i < imax; ++i) { Transform t = mChildren[i]; float distance = t.localPosition.y - center.y; if (distance < -extents) { Vector3 pos = t.localPosition; pos.y += ext2; distance = pos.y - center.y; int realIndex = Mathf.RoundToInt(pos.y / itemSize); if (minIndex == maxIndex || (minIndex <= realIndex && realIndex <= maxIndex)) { t.localPosition = pos; UpdateItem(t, i); } else { allWithinRange = false; } } else if (distance > extents) { Vector3 pos = t.localPosition; pos.y -= ext2; distance = pos.y - center.y; int realIndex = Mathf.RoundToInt(pos.y / itemSize); if (minIndex == maxIndex || (minIndex <= realIndex && realIndex <= maxIndex)) { t.localPosition = pos; UpdateItem(t, i); } else { allWithinRange = false; } } else if (mFirstTime) { UpdateItem(t, i); } if (cullContent) { distance += mPanel.clipOffset.y - mTrans.localPosition.y; if (!UICamera.IsPressed(t.gameObject)) { NGUITools.SetActive(t.gameObject, (distance > min && distance < max), false); } } } } mScroll.restrictWithinPanel = !allWithinRange; }
/// <summary> /// Start the dragging operation. /// </summary> public virtual void StartDragging() { if (!interactable) { return; } if (!mDragging) { if (cloneOnDrag) { mPressed = false; GameObject clone = transform.parent.gameObject.AddChild(gameObject); clone.transform.localPosition = transform.localPosition; clone.transform.localRotation = transform.localRotation; clone.transform.localScale = transform.localScale; Transform cloneTF = clone.transform.FindRecursively("icon"); if (cloneTF) { UISprite cloneSprite = clone.GetComponent <UISprite>(); UISprite iconSprite = cloneTF.GetComponent <UISprite>(); cloneSprite.depth = cloneSprite.depth + 2; iconSprite.depth = iconSprite.depth + 2; } UIButtonColor bc = clone.GetComponent <UIButtonColor>(); if (bc != null) { bc.defaultColor = GetComponent <UIButtonColor>().defaultColor; } if (mTouch != null && mTouch.pressed == gameObject) { mTouch.current = clone; mTouch.pressed = clone; mTouch.dragged = clone; mTouch.last = clone; } UIDragDropItem item = clone.GetComponent <UIDragDropItem>(); item.mTouch = mTouch; item.mPressed = true; item.mDragging = true; item.Start(); item.OnClone(gameObject); item.OnDragDropStart(); if (UICamera.currentTouch == null) { UICamera.currentTouch = mTouch; } mTouch = null; UICamera.Notify(gameObject, "OnPress", false); UICamera.Notify(gameObject, "OnHover", false); } else { mDragging = true; OnDragDropStart(); } } }
//void CreateUGUI() //{ // var canvasObj = new GameObject("UICanvas"); // UICanvas = canvasObj.AddComponent<Canvas>(); // UICanvas.renderMode = RenderMode.ScreenSpaceOverlay; // //UICanvas.worldCamera = UiCamera.cachedCamera; // canvasObj.AddComponent<GraphicRaycaster>(); // var scaler = canvasObj.AddComponent<CanvasScaler>(); // scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; // 屏幕固定大小 // scaler.referenceResolution = new Vector2(1080, 1920); // var evtSysObj = new GameObject("EventSystem"); // KTool.SetChild(evtSysObj, canvasObj); // evtSysObj.AddComponent<EventSystem>(); //} private void CreateUIRoot() { GameObject uiRootobj = GameObject.Find("NGUIRoot") ?? new GameObject("NGUIRoot"); UiRoot = uiRootobj.GetComponent<UIRoot>() ?? uiRootobj.AddComponent<UIRoot>(); Debuger.Assert(UiRoot); UiRoot.scalingStyle = UIRoot.Scaling.FixedSizeOnMobiles; // 尝试将NGUI转化成跟2dToolkit镜头一致显示 UiRoot.manualHeight = 1080; //GameDef.ScreenPixelY;//(int)(GameDef.ScreenPixelY / (GameDef.ScreenPixelY / 2f / GameDef.DefaultPixelPerMeters)); // fit width! //UiRoot.manualWidth = 1920;//GameDef.ScreenPixelX; // 屏幕中间位置 //UiRoot.transform.localPosition = new Vector3(GameDef.ScreenPixelX / 2f / GameDef.DefaultPixelPerMeters, // GameDef.ScreenPixelY / 2f / GameDef.DefaultPixelPerMeters, -50); //var scale = 1 / GameDef.DefaultPixelPerMeters; //// 覆盖NGUI的Uiroot自动缩放 //UiRoot.transform.localScale = new Vector3(scale, scale, scale); //UiRoot.enabled = false; GameObject panelRootObj = new GameObject("PanelRoot"); KTool.SetChild(panelRootObj.transform, uiRootobj.transform); Transform panelTrans = panelRootObj.transform; PanelRoot = panelRootObj.AddComponent<UIPanel>(); Debuger.Assert(PanelRoot); PanelRoot.generateNormals = true; var uiCamTrans = uiRootobj.transform.Find("UICamera"); GameObject uiCamObj = uiCamTrans != null ? uiCamTrans.gameObject : new GameObject("UICamera"); KTool.SetChild(uiCamObj.transform, UiRoot.transform); UiCamera = uiCamObj.GetComponent<UICamera>() ?? uiCamObj.AddComponent<UICamera>(); UiCamera.cachedCamera.cullingMask = 1 << (int)UnityLayerDef.UI; UiCamera.cachedCamera.clearFlags = CameraClearFlags.Depth; UiCamera.cachedCamera.orthographic = true; UiCamera.cachedCamera.orthographicSize = GameDef.ScreenPixelY / GameDef.DefaultPixelPerMeters / 2f; // 9.6,一屏19.2米,跟GameCamera一致 UiCamera.cachedCamera.nearClipPlane = -500; UiCamera.cachedCamera.farClipPlane = 500; foreach (UIAnchor.Side side in Enum.GetValues(typeof(UIAnchor.Side))) { GameObject anchorObj = new GameObject(side.ToString()); KTool.SetChild(anchorObj.transform, panelTrans); AnchorSide[side.ToString()] = anchorObj.transform; } GameObject nullAnchor = new GameObject("Null"); KTool.SetChild(nullAnchor.transform, panelTrans); AnchorSide["Null"] = nullAnchor.transform; AnchorSide[""] = AnchorSide[UIAnchor.Side.Center.ToString()]; // default NGUITools.SetLayer(uiRootobj, (int)UnityLayerDef.UI); PressWidget = new GameObject("PressWidget").AddComponent<UIWidget>(); NGUITools.SetLayer(PressWidget.gameObject, (int)UnityLayerDef.UI); KTool.SetChild(PressWidget.gameObject, panelRootObj); PressWidget.SetDimensions(2000, 2000); var col = PressWidget.gameObject.AddComponent<BoxCollider>(); col.size = new Vector3(2000, 2000); PressWidget.autoResizeBoxCollider = true; PressWidget.gameObject.SetActive(false); //UICamera.onDragStart = (go) => //{ // if (go != null) // 点击任意NGUI控件,出现阻挡 // PressWidget.gameObject.SetActive(true); //}; //UICamera.onPress = (go, state) => //{ // if (!state) // 点击任意NGUI控件,出现阻挡 // PressWidget.gameObject.SetActive(false); // //if (go != null) // //{ // // if (go.GetComponent<UIButton>() == null) // // { // // if (go.GetComponent<UIEventListener>() != null && go.GetComponent<UISprite>() != null) // // { // // if (Debug.isDebugBuild) // // { // // Debug.LogWarning("自动加UIButton和ButtonScale - " + go.name, go); // // } // // // 当不包含ButtonScale动画 // // // 并且拥有EventListener和UISprite! // // // 统一加上ButtonScale! // // var bScale = go.GetComponent<UIButtonScale>() ?? go.AddComponent<UIButtonScale>(); // // bScale.pressed = bScale.hover; // // bScale.hover = Vector3.one; // // var bColor = go.GetComponent<UIButton>() ?? go.AddComponent<UIButton>(); // // bColor.hover = Color.white; // // bColor.pressed = Color.white*.8f; // 小小灰 // // } // // } // //} //}; }
protected virtual bool IsModifierActive() { if (this.modifier == UIKeyBinding.Modifier.Any) { return(true); } if (this.modifier == UIKeyBinding.Modifier.Alt) { if (UICamera.GetKey(KeyCode.LeftAlt) || UICamera.GetKey(KeyCode.RightAlt)) { return(true); } } else if (this.modifier == UIKeyBinding.Modifier.Control) { if (UICamera.GetKey(KeyCode.LeftControl) || UICamera.GetKey(KeyCode.RightControl)) { return(true); } } else if (this.modifier == UIKeyBinding.Modifier.Shift) { if (UICamera.GetKey(KeyCode.LeftShift) || UICamera.GetKey(KeyCode.RightShift)) { return(true); } } else if (this.modifier == UIKeyBinding.Modifier.None) { return(!UICamera.GetKey(KeyCode.LeftAlt) && !UICamera.GetKey(KeyCode.RightAlt) && !UICamera.GetKey(KeyCode.LeftControl) && !UICamera.GetKey(KeyCode.RightControl) && !UICamera.GetKey(KeyCode.LeftShift) && !UICamera.GetKey(KeyCode.RightShift)); } return(false); }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update() { // Only the first UI layer should be processing events if (!Application.isPlaying || !handlesEvents) { return; } current = this; if (useTouch) { if (mIsEditor) { // Only process mouse events while in the editor ProcessMouse(); } else { // Process touch events first ProcessTouches(); // If we want to process mouse events, only do so if there are no active touch events, // otherwise there is going to be event duplication as Unity treats touch events as mouse events. if (useMouse && Input.touchCount == 0) { ProcessMouse(); } } } else if (useMouse) { ProcessMouse(); } // Custom input processing if (onCustomInput != null) { onCustomInput(); } // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mCurrentSelection != null && ((cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) || (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)))) { selectedObject = null; } // Forward the input to the selected object if (mCurrentSelection != null) { string input = Input.inputString; // Adding support for some macs only having the "Delete" key instead of "Backspace" if (useKeyboard && Input.GetKeyDown(KeyCode.Delete)) { input += "\b"; } if (input.Length > 0) { if (!stickyTooltip && mTooltip != null) { ShowTooltip(false); } Notify(mCurrentSelection, "OnInput", input); } } else { inputHasFocus = false; } // Update the keyboard and joystick events if (mCurrentSelection != null) { ProcessOthers(); } // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = Input.GetAxis(scrollAxisName); if (scroll != 0f) { Notify(mHover, "OnScroll", scroll); } if (showTooltips && mTooltipTime != 0f && (mTooltipTime < Time.realtimeSinceStartup || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { // Only the first UI layer should be processing events #if UNITY_EDITOR if (!Application.isPlaying || !handlesEvents) return; #else if (!handlesEvents) return; #endif current = this; NGUIDebug.debugRaycast = debug; // Process touch events first if (useTouch) ProcessTouches (); else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Update the keyboard and joystick events if ((useKeyboard || useController) && !disableController) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = !string.IsNullOrEmpty(scrollAxisName) ? GetAxis(scrollAxisName) : 0f; if (scroll != 0f) { if (onScroll != null) onScroll(mHover, scroll); Notify(mHover, "OnScroll", scroll); } if (showTooltips && mTooltipTime != 0f && !UIPopupList.isOpen && mMouse[0].dragged == null && (mTooltipTime < RealTime.time || GetKey(KeyCode.LeftShift) || GetKey(KeyCode.RightShift))) { currentTouch = mMouse[0]; currentTouchID = -1; ShowTooltip(mHover); } } if (mTooltip != null && !NGUITools.GetActive(mTooltip)) ShowTooltip(null); current = null; currentTouchID = -100; }
/// <summary> /// Start the dragging operation. /// </summary> void OnDragStart() { if (!enabled || mTouchID != int.MinValue) { return; } // If we have a restriction, check to see if its condition has been met first if (restriction != Restriction.None) { if (restriction == Restriction.Horizontal) { Vector2 delta = UICamera.currentTouch.totalDelta; if (Mathf.Abs(delta.x) < Mathf.Abs(delta.y)) { return; } } else if (restriction == Restriction.Vertical) { Vector2 delta = UICamera.currentTouch.totalDelta; if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y)) { return; } } else if (restriction == Restriction.PressAndHold) { if (mPressTime + 1f > RealTime.time) { return; } } } if (cloneOnDrag) { GameObject clone = NGUITools.AddChild(transform.parent.gameObject, gameObject); clone.transform.localPosition = transform.localPosition; clone.transform.localRotation = transform.localRotation; clone.transform.localScale = transform.localScale; UIButtonColor bc = clone.GetComponent <UIButtonColor>(); if (bc != null) { bc.defaultColor = GetComponent <UIButtonColor>().defaultColor; } UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", false); UICamera.currentTouch.pressed = clone; UICamera.currentTouch.dragged = clone; UIDragDropItem item = clone.GetComponent <UIDragDropItem>(); item.Start(); item.OnDragDropStart(); } else { OnDragDropStart(); } }
/// <summary> /// Selection change is delayed on purpose. This way selection changes during event processing won't cause /// the newly selected widget to continue processing when it is it's turn. Example: pressing 'tab' on one /// button selects the next button, and then it also processes its 'tab' in turn, selecting the next one. /// </summary> System.Collections.IEnumerator ChangeSelection () { yield return new WaitForEndOfFrame(); mCurrentSelection = mNextSelection; mNextSelection = null; if (mCurrentSelection != null) { current = this; currentCamera = mCam; UICamera.currentScheme = mNextScheme; Notify(mCurrentSelection, "OnSelect", true); current = null; } }
/// <summary> /// Static comparison function used for sorting. /// </summary> static int CompareFunc (UICamera a, UICamera b) { if (a.cachedCamera.depth < b.cachedCamera.depth) return 1; if (a.cachedCamera.depth > b.cachedCamera.depth) return -1; return 0; }
/// <summary> /// Handles & interaction. /// </summary> public void OnSceneGUI() { if (Selection.objects.Length > 1) { return; } UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer); #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 if (cam == null || !cam.cachedCamera.isOrthoGraphic) { return; } #else if (cam == null || !cam.cachedCamera.orthographic) { return; } #endif NGUIEditorTools.HideMoveTool(true); if (!UIWidget.showHandles) { return; } Event e = Event.current; int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive); EventType type = e.GetTypeForControl(id); Transform t = mPanel.cachedTransform; Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners); // Time to figure out what kind of action is underneath the mouse UIWidgetInspector.Action actionUnderMouse = mAction; Color handlesColor = new Color(0.5f, 0f, 0.5f); NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor); NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor); NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor); NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor); if (mPanel.isAnchored) { UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id); UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id); UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id); UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id); } if (type == EventType.Repaint) { bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides; if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control) { showDetails = true; } if (NGUITools.GetActive(mPanel) && mPanel.parent == null) { showDetails = true; } if (showDetails) { NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height)); } } bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None); // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels. if (canResize && mPanel.isAnchored) { Quaternion rot = mPanel.cachedTransform.localRotation; if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f) { canResize = false; } } bool[] resizable = new bool[8]; resizable[4] = canResize; // left resizable[5] = canResize; // top resizable[6] = canResize; // right resizable[7] = canResize; // bottom resizable[0] = resizable[7] && resizable[4]; // bottom-left resizable[1] = resizable[5] && resizable[4]; // top-left resizable[2] = resizable[5] && resizable[6]; // top-right resizable[3] = resizable[7] && resizable[6]; // bottom-right UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse); switch (type) { case EventType.Repaint: { Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]); Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]); if ((v2 - v0).magnitude > 60f) { Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]); Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]); Handles.BeginGUI(); { for (int i = 0; i < 4; ++i) { DrawKnob(handles[i], id, resizable[i]); } if (Mathf.Abs(v1.y - v0.y) > 80f) { if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0) { DrawKnob(handles[4], id, resizable[4]); } if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0) { DrawKnob(handles[6], id, resizable[6]); } } if (Mathf.Abs(v3.x - v0.x) > 80f) { if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0) { DrawKnob(handles[5], id, resizable[5]); } if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0) { DrawKnob(handles[7], id, resizable[7]); } } } Handles.EndGUI(); } } break; case EventType.MouseDown: { if (actionUnderMouse != UIWidgetInspector.Action.None) { mStartMouse = e.mousePosition; mAllowSelection = true; if (e.button == 1) { if (e.modifiers == 0) { GUIUtility.hotControl = GUIUtility.keyboardControl = id; e.Use(); } } else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None && UIWidgetInspector.Raycast(handles, out mStartDrag)) { mWorldPos = t.position; mLocalPos = t.localPosition; mStartRot = t.localRotation.eulerAngles; mStartDir = mStartDrag - t.position; mStartCR = mPanel.baseClipRegion; mDragPivot = pivotUnderMouse; mActionUnderMouse = actionUnderMouse; GUIUtility.hotControl = GUIUtility.keyboardControl = id; e.Use(); } } } break; case EventType.MouseUp: { if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; if (e.button < 2) { bool handled = false; if (e.button == 1) { // Right-click: Open a context menu listing all widgets underneath NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition); handled = true; } else if (mAction == UIWidgetInspector.Action.None) { if (mAllowSelection) { // Left-click: Select the topmost widget NGUIEditorTools.SelectWidget(e.mousePosition); handled = true; } } else { // Finished dragging something Vector3 pos = t.localPosition; pos.x = Mathf.Round(pos.x); pos.y = Mathf.Round(pos.y); pos.z = Mathf.Round(pos.z); t.localPosition = pos; handled = true; } if (handled) { e.Use(); } } // Clear the actions mActionUnderMouse = UIWidgetInspector.Action.None; mAction = UIWidgetInspector.Action.None; } else if (mAllowSelection) { List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition); if (widgets.Count > 0) { Selection.activeGameObject = widgets[0].gameObject; } } mAllowSelection = true; } break; case EventType.MouseDrag: { // Prevent selection once the drag operation begins bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f; if (dragStarted) { mAllowSelection = false; } if (GUIUtility.hotControl == id) { e.Use(); if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None) { Vector3 pos; if (UIWidgetInspector.Raycast(handles, out pos)) { if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None) { // Wait until the mouse moves by more than a few pixels if (dragStarted) { if (mActionUnderMouse == UIWidgetInspector.Action.Move) { NGUISnap.Recalculate(mPanel); } else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate) { mStartRot = t.localRotation.eulerAngles; mStartDir = mStartDrag - t.position; } else if (mActionUnderMouse == UIWidgetInspector.Action.Scale) { mStartCR = mPanel.baseClipRegion; mDragPivot = pivotUnderMouse; } mAction = actionUnderMouse; } } if (mAction != UIWidgetInspector.Action.None) { NGUIEditorTools.RegisterUndo("Change Rect", t); NGUIEditorTools.RegisterUndo("Change Rect", mPanel); if (mAction == UIWidgetInspector.Action.Move) { Vector3 before = t.position; Vector3 beforeLocal = t.localPosition; t.position = mWorldPos + (pos - mStartDrag); pos = NGUISnap.Snap(t.localPosition, mPanel.localCorners, e.modifiers != EventModifiers.Control) - beforeLocal; t.position = before; NGUIMath.MoveRect(mPanel, pos.x, pos.y); } else if (mAction == UIWidgetInspector.Action.Rotate) { Vector3 dir = pos - t.position; float angle = Vector3.Angle(mStartDir, dir); if (angle > 0f) { float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward); if (dot < 0f) { angle = -angle; } angle = mStartRot.z + angle; angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ? Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle); t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle); } } else if (mAction == UIWidgetInspector.Action.Scale) { // World-space delta since the drag started Vector3 delta = pos - mStartDrag; // Adjust the widget's position and scale based on the delta, restricted by the pivot AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot); } } } } } } break; case EventType.KeyDown: { if (e.keyCode == KeyCode.UpArrow) { NGUIEditorTools.RegisterUndo("Nudge Rect", t); NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel); NGUIMath.MoveRect(mPanel, 0f, 1f); e.Use(); } else if (e.keyCode == KeyCode.DownArrow) { NGUIEditorTools.RegisterUndo("Nudge Rect", t); NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel); NGUIMath.MoveRect(mPanel, 0f, -1f); e.Use(); } else if (e.keyCode == KeyCode.LeftArrow) { NGUIEditorTools.RegisterUndo("Nudge Rect", t); NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel); NGUIMath.MoveRect(mPanel, -1f, 0f); e.Use(); } else if (e.keyCode == KeyCode.RightArrow) { NGUIEditorTools.RegisterUndo("Nudge Rect", t); NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel); NGUIMath.MoveRect(mPanel, 1f, 0f); e.Use(); } else if (e.keyCode == KeyCode.Escape) { if (GUIUtility.hotControl == id) { if (mAction != UIWidgetInspector.Action.None) { Undo.PerformUndo(); } GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; mActionUnderMouse = UIWidgetInspector.Action.None; mAction = UIWidgetInspector.Action.None; e.Use(); } else { Selection.activeGameObject = null; } } } break; } }
public override void OnInspectorGUI() { UICamera cam = target as UICamera; GUILayout.Space(3f); serializedObject.Update(); SerializedProperty et = serializedObject.FindProperty("eventType"); if (et.hasMultipleDifferentValues) { EditorGUILayout.PropertyField(et); } else { string[] options = new string[] { "3D World", "3D UI", "2D World", "2D UI" }; int val = EditorGUILayout.Popup("Event Type", et.intValue, options); if (val != et.intValue) { et.intValue = val; } } if (UICamera.eventHandler != cam) { EditorGUILayout.PropertyField(serializedObject.FindProperty("eventReceiverMask"), new GUIContent("Event Mask")); serializedObject.ApplyModifiedProperties(); EditorGUILayout.HelpBox("All other settings are inherited from the First Camera.", MessageType.Info); if (GUILayout.Button("Select the First Camera")) { Selection.activeGameObject = UICamera.eventHandler.gameObject; } } else { SerializedProperty mouse = serializedObject.FindProperty("useMouse"); SerializedProperty touch = serializedObject.FindProperty("useTouch"); SerializedProperty keyboard = serializedObject.FindProperty("useKeyboard"); SerializedProperty controller = serializedObject.FindProperty("useController"); EditorGUILayout.PropertyField(serializedObject.FindProperty("eventReceiverMask"), new GUIContent("Event Mask")); EditorGUILayout.PropertyField(serializedObject.FindProperty("debug")); EditorGUI.BeginDisabledGroup(!mouse.boolValue && !touch.boolValue); { EditorGUILayout.PropertyField(serializedObject.FindProperty("allowMultiTouch")); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!mouse.boolValue); { EditorGUILayout.PropertyField(serializedObject.FindProperty("stickyTooltip")); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(serializedObject.FindProperty("tooltipDelay")); GUILayout.Label("seconds", GUILayout.MinWidth(60f)); GUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); GUILayout.BeginHorizontal(); SerializedProperty rd = serializedObject.FindProperty("rangeDistance"); EditorGUILayout.PropertyField(rd, new GUIContent("Raycast Range")); GUILayout.Label(rd.floatValue < 0f ? "unlimited" : "units", GUILayout.MinWidth(60f)); GUILayout.EndHorizontal(); NGUIEditorTools.SetLabelWidth(80f); if (NGUIEditorTools.DrawHeader("Event Sources")) { NGUIEditorTools.BeginContents(); { GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(mouse, new GUIContent("Mouse"), GUILayout.MinWidth(100f)); EditorGUILayout.PropertyField(touch, new GUIContent("Touch"), GUILayout.MinWidth(100f)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(keyboard, new GUIContent("Keyboard"), GUILayout.MinWidth(100f)); EditorGUILayout.PropertyField(controller, new GUIContent("Controller"), GUILayout.MinWidth(100f)); GUILayout.EndHorizontal(); } NGUIEditorTools.EndContents(); } if ((mouse.boolValue || touch.boolValue) && NGUIEditorTools.DrawHeader("Thresholds")) { NGUIEditorTools.BeginContents(); { EditorGUI.BeginDisabledGroup(!mouse.boolValue); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(serializedObject.FindProperty("mouseDragThreshold"), new GUIContent("Mouse Drag"), GUILayout.Width(120f)); GUILayout.Label("pixels"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(serializedObject.FindProperty("mouseClickThreshold"), new GUIContent("Mouse Click"), GUILayout.Width(120f)); GUILayout.Label("pixels"); GUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!touch.boolValue); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(serializedObject.FindProperty("touchDragThreshold"), new GUIContent("Touch Drag"), GUILayout.Width(120f)); GUILayout.Label("pixels"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(serializedObject.FindProperty("touchClickThreshold"), new GUIContent("Touch Tap"), GUILayout.Width(120f)); GUILayout.Label("pixels"); GUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); } NGUIEditorTools.EndContents(); } if ((mouse.boolValue || keyboard.boolValue || controller.boolValue) && NGUIEditorTools.DrawHeader("Axes and Keys")) { NGUIEditorTools.BeginContents(); { EditorGUILayout.PropertyField(serializedObject.FindProperty("horizontalAxisName"), new GUIContent("Horizontal")); EditorGUILayout.PropertyField(serializedObject.FindProperty("verticalAxisName"), new GUIContent("Vertical")); EditorGUILayout.PropertyField(serializedObject.FindProperty("scrollAxisName"), new GUIContent("Scroll")); EditorGUILayout.PropertyField(serializedObject.FindProperty("submitKey0"), new GUIContent("Submit 1")); EditorGUILayout.PropertyField(serializedObject.FindProperty("submitKey1"), new GUIContent("Submit 2")); EditorGUILayout.PropertyField(serializedObject.FindProperty("cancelKey0"), new GUIContent("Cancel 1")); EditorGUILayout.PropertyField(serializedObject.FindProperty("cancelKey1"), new GUIContent("Cancel 2")); } NGUIEditorTools.EndContents(); } serializedObject.ApplyModifiedProperties(); } }
public virtual void WrapContent() { float num = (float)(this.itemSize * this.mChildren.Count) * 0.5f; Vector3[] worldCorners = this.mPanel.worldCorners; for (int i = 0; i < 4; i++) { Vector3 vector = worldCorners[i]; vector = this.mTrans.InverseTransformPoint(vector); worldCorners[i] = vector; } Vector3 vector2 = Vector3.Lerp(worldCorners[0], worldCorners[2], 0.5f); bool flag = true; float num2 = num * 2f; if (this.mHorizontal) { float num3 = worldCorners[0].x - (float)this.itemSize; float num4 = worldCorners[2].x + (float)this.itemSize; int j = 0; int count = this.mChildren.Count; while (j < count) { Transform transform = this.mChildren[j]; float num5 = transform.localPosition.x - vector2.x; if (num5 < -num) { Vector3 localPosition = transform.localPosition; localPosition.x += num2; num5 = localPosition.x - vector2.x; int num6 = Mathf.RoundToInt(localPosition.x / (float)this.itemSize); if (this.minIndex == this.maxIndex || (this.minIndex <= num6 && num6 <= this.maxIndex)) { transform.localPosition = localPosition; this.UpdateItem(transform, j); } else { flag = false; } } else if (num5 > num) { Vector3 localPosition2 = transform.localPosition; localPosition2.x -= num2; num5 = localPosition2.x - vector2.x; int num7 = Mathf.RoundToInt(localPosition2.x / (float)this.itemSize); if (this.minIndex == this.maxIndex || (this.minIndex <= num7 && num7 <= this.maxIndex)) { transform.localPosition = localPosition2; this.UpdateItem(transform, j); } else { flag = false; } } else if (this.mFirstTime) { this.UpdateItem(transform, j); } if (this.cullContent) { num5 += this.mPanel.clipOffset.x - this.mTrans.localPosition.x; if (!UICamera.IsPressed(transform.gameObject)) { NGUITools.SetActive(transform.gameObject, num5 > num3 && num5 < num4, false); } } j++; } } else { float num8 = worldCorners[0].y - (float)this.itemSize; float num9 = worldCorners[2].y + (float)this.itemSize; int k = 0; int count2 = this.mChildren.Count; while (k < count2) { Transform transform2 = this.mChildren[k]; float num10 = transform2.localPosition.y - vector2.y; if (num10 < -num) { Vector3 localPosition3 = transform2.localPosition; localPosition3.y += num2; num10 = localPosition3.y - vector2.y; int num11 = Mathf.RoundToInt(localPosition3.y / (float)this.itemSize); if (this.minIndex == this.maxIndex || (this.minIndex <= num11 && num11 <= this.maxIndex)) { transform2.localPosition = localPosition3; this.UpdateItem(transform2, k); } else { flag = false; } } else if (num10 > num) { Vector3 localPosition4 = transform2.localPosition; localPosition4.y -= num2; num10 = localPosition4.y - vector2.y; int num12 = Mathf.RoundToInt(localPosition4.y / (float)this.itemSize); if (this.minIndex == this.maxIndex || (this.minIndex <= num12 && num12 <= this.maxIndex)) { transform2.localPosition = localPosition4; this.UpdateItem(transform2, k); } else { flag = false; } } else if (this.mFirstTime) { this.UpdateItem(transform2, k); } if (this.cullContent) { num10 += this.mPanel.clipOffset.y - this.mTrans.localPosition.y; if (!UICamera.IsPressed(transform2.gameObject)) { NGUITools.SetActive(transform2.gameObject, num10 > num8 && num10 < num9, false); } } k++; } } this.mScroll.restrictWithinPanel = !flag; }
// Token: 0x060002FF RID: 767 RVA: 0x00023AF0 File Offset: 0x00021CF0 private void Update() { if (!Application.isPlaying || !this.handlesEvents) { return; } UICamera.current = this; if (this.useMouse || (this.useTouch && this.mIsEditor)) { this.ProcessMouse(); } if (this.useTouch) { this.ProcessTouches(); } if (UICamera.onCustomInput != null) { UICamera.onCustomInput(); } if (this.useMouse && UICamera.mSel != null && ((this.cancelKey0 != KeyCode.None && Input.GetKeyDown(this.cancelKey0)) || (this.cancelKey1 != KeyCode.None && Input.GetKeyDown(this.cancelKey1)))) { UICamera.selectedObject = null; } if (UICamera.mSel != null) { string inputString = Input.inputString; UICamera.lastInputEvents += inputString; if (this.useKeyboard && Input.GetKeyDown(KeyCode.Delete) && UICamera.lastInputEvents.LastIndexOf('\b') == -1) { UICamera.lastInputEvents += "\b"; } if (UICamera.lastInputEvents.Length > 0) { if (!this.stickyTooltip && this.mTooltip != null) { this.ShowTooltip(false); } UICamera.Notify(UICamera.mSel, "OnInput", UICamera.lastInputEvents); UICamera.lastInputEvents = string.Empty; } } else { UICamera.inputHasFocus = false; } if (UICamera.mSel != null) { this.ProcessOthers(); } if (this.useMouse && UICamera.mHover != null) { float axis = Input.GetAxis(this.scrollAxisName); if (axis != 0f) { UICamera.Notify(UICamera.mHover, "OnScroll", axis); } if (UICamera.showTooltips && this.mTooltipTime != 0f && (this.mTooltipTime < Time.realtimeSinceStartup || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { this.mTooltip = UICamera.mHover; this.ShowTooltip(true); } } UICamera.current = null; }
private void Update() { if (!this.handlesEvents) { return; } UICamera.current = this; if (this.useTouch) { this.ProcessTouches(); } else if (this.useMouse) { this.ProcessMouse(); } if (UICamera.onCustomInput != null) { UICamera.onCustomInput(); } if (this.useMouse && UICamera.mCurrentSelection != null) { if (this.cancelKey0 != KeyCode.None && UICamera.GetKeyDown(this.cancelKey0)) { UICamera.currentScheme = UICamera.ControlScheme.Controller; UICamera.currentKey = this.cancelKey0; UICamera.selectedObject = null; } else if (this.cancelKey1 != KeyCode.None && UICamera.GetKeyDown(this.cancelKey1)) { UICamera.currentScheme = UICamera.ControlScheme.Controller; UICamera.currentKey = this.cancelKey1; UICamera.selectedObject = null; } } if (UICamera.mCurrentSelection == null) { UICamera.inputHasFocus = false; } if (UICamera.mCurrentSelection != null) { this.ProcessOthers(); } if (this.useMouse && UICamera.mHover != null) { float num = string.IsNullOrEmpty(this.scrollAxisName) ? 0f : UICamera.GetAxis(this.scrollAxisName); if (num != 0f) { if (UICamera.onScroll != null) { UICamera.onScroll(UICamera.mHover, num); } UICamera.Notify(UICamera.mHover, "OnScroll", num); } if (UICamera.showTooltips && this.mTooltipTime != 0f && (this.mTooltipTime < RealTime.time || UICamera.GetKey(KeyCode.LeftShift) || UICamera.GetKey(KeyCode.RightShift))) { this.mTooltip = UICamera.mHover; this.ShowTooltip(true); } } UICamera.current = null; UICamera.currentTouchID = -100; }
// Token: 0x06000300 RID: 768 RVA: 0x00023D38 File Offset: 0x00021F38 public void ProcessMouse() { bool flag = this.useMouse && Time.timeScale < 0.9f; if (!flag) { for (int i = 0; i < 3; i++) { if (Input.GetMouseButton(i) || Input.GetMouseButtonUp(i)) { flag = true; break; } } } UICamera.mMouse[0].pos = Input.mousePosition; UICamera.mMouse[0].delta = UICamera.mMouse[0].pos - UICamera.lastTouchPosition; bool flag2 = UICamera.mMouse[0].pos != UICamera.lastTouchPosition; UICamera.lastTouchPosition = UICamera.mMouse[0].pos; if (flag) { UICamera.hoveredObject = ((!UICamera.Raycast(Input.mousePosition, ref UICamera.lastHit)) ? UICamera.fallThrough : UICamera.lastHit.collider.gameObject); if (UICamera.hoveredObject == null) { UICamera.hoveredObject = UICamera.genericEventHandler; } UICamera.mMouse[0].current = UICamera.hoveredObject; } for (int j = 1; j < 3; j++) { UICamera.mMouse[j].pos = UICamera.mMouse[0].pos; UICamera.mMouse[j].delta = UICamera.mMouse[0].delta; UICamera.mMouse[j].current = UICamera.mMouse[0].current; } bool flag3 = false; for (int k = 0; k < 3; k++) { if (Input.GetMouseButton(k)) { flag3 = true; break; } } if (flag3) { this.mTooltipTime = 0f; } else if (this.useMouse && flag2 && (!this.stickyTooltip || UICamera.mHover != UICamera.mMouse[0].current)) { if (this.mTooltipTime != 0f) { this.mTooltipTime = Time.realtimeSinceStartup + this.tooltipDelay; } else if (this.mTooltip != null) { this.ShowTooltip(false); } } if (this.useMouse && !flag3 && UICamera.mHover != null && UICamera.mHover != UICamera.mMouse[0].current) { if (this.mTooltip != null) { this.ShowTooltip(false); } UICamera.Highlight(UICamera.mHover, false); UICamera.mHover = null; } if (this.useMouse) { for (int l = 0; l < 3; l++) { bool mouseButtonDown = Input.GetMouseButtonDown(l); bool mouseButtonUp = Input.GetMouseButtonUp(l); UICamera.currentTouch = UICamera.mMouse[l]; UICamera.currentTouchID = -1 - l; if (mouseButtonDown) { UICamera.currentTouch.pressedCam = UICamera.currentCamera; } else if (UICamera.currentTouch.pressed != null) { UICamera.currentCamera = UICamera.currentTouch.pressedCam; } this.ProcessTouch(mouseButtonDown, mouseButtonUp); } UICamera.currentTouch = null; } if (this.useMouse && !flag3 && UICamera.mHover != UICamera.mMouse[0].current) { this.mTooltipTime = Time.realtimeSinceStartup + this.tooltipDelay; UICamera.mHover = UICamera.mMouse[0].current; UICamera.Highlight(UICamera.mHover, true); } }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { #if UNITY_ANDROID && !UNITY_EDITOR for (int playerNum = 0; playerNum < OuyaController.MAX_CONTROLLERS; ++playerNum) { if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_O)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnClick", null); } if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_A)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.Escape); } if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_DPAD_UP)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.UpArrow); } else if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_DPAD_DOWN)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.DownArrow); } if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_DPAD_LEFT)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.LeftArrow); } else if (OuyaSDK.OuyaInput.GetButtonUp(playerNum, OuyaController.BUTTON_DPAD_RIGHT)) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.RightArrow); } } #endif // Only the first UI layer should be processing events #if UNITY_EDITOR if (!Application.isPlaying || !handlesEvents) return; #else if (!handlesEvents) return; #endif current = this; // Process touch events first if (useTouch) ProcessTouches (); else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mCurrentSelection != null) { if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey0; selectedObject = null; } else if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey1; selectedObject = null; } } // If nothing is selected, input focus is lost if (mCurrentSelection == null) inputHasFocus = false; // Update the keyboard and joystick events if (mCurrentSelection != null) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = !string.IsNullOrEmpty(scrollAxisName) ? Input.GetAxis(scrollAxisName) : 0f; if (scroll != 0f) Notify(mHover, "OnScroll", scroll); if (showTooltips && mTooltipTime != 0f && (mTooltipTime < RealTime.time || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; }
// Token: 0x06000302 RID: 770 RVA: 0x000242A8 File Offset: 0x000224A8 public void ProcessOthers() { UICamera.currentTouchID = -100; UICamera.currentTouch = UICamera.mController; UICamera.inputHasFocus = (UICamera.mSel != null && UICamera.mSel.GetComponent <UIInput>() != null); bool flag = (this.submitKey0 != KeyCode.None && Input.GetKeyDown(this.submitKey0)) || (this.submitKey1 != KeyCode.None && Input.GetKeyDown(this.submitKey1)); bool flag2 = (this.submitKey0 != KeyCode.None && Input.GetKeyUp(this.submitKey0)) || (this.submitKey1 != KeyCode.None && Input.GetKeyUp(this.submitKey1)); if (flag || flag2) { UICamera.currentTouch.current = UICamera.mSel; this.ProcessTouch(flag, flag2); UICamera.currentTouch.current = null; } int num = 0; int num2 = 0; if (this.useKeyboard) { if (UICamera.inputHasFocus) { num += UICamera.GetDirection(KeyCode.UpArrow, KeyCode.DownArrow); num2 += UICamera.GetDirection(KeyCode.RightArrow, KeyCode.LeftArrow); } else { num += UICamera.GetDirection(KeyCode.W, KeyCode.UpArrow, KeyCode.S, KeyCode.DownArrow); num2 += UICamera.GetDirection(KeyCode.D, KeyCode.RightArrow, KeyCode.A, KeyCode.LeftArrow); } } if (this.useController) { if (!string.IsNullOrEmpty(this.verticalAxisName)) { num += UICamera.GetDirection(this.verticalAxisName); } if (!string.IsNullOrEmpty(this.horizontalAxisName)) { num2 += UICamera.GetDirection(this.horizontalAxisName); } } if (num != 0) { UICamera.Notify(UICamera.mSel, "OnKey", (num <= 0) ? KeyCode.DownArrow : KeyCode.UpArrow); } if (num2 != 0) { UICamera.Notify(UICamera.mSel, "OnKey", (num2 <= 0) ? KeyCode.LeftArrow : KeyCode.RightArrow); } if (this.useKeyboard && Input.GetKeyDown(KeyCode.Tab)) { UICamera.Notify(UICamera.mSel, "OnKey", KeyCode.Tab); } if (this.cancelKey0 != KeyCode.None && Input.GetKeyDown(this.cancelKey0)) { UICamera.Notify(UICamera.mSel, "OnKey", KeyCode.Escape); } if (this.cancelKey1 != KeyCode.None && Input.GetKeyDown(this.cancelKey1)) { UICamera.Notify(UICamera.mSel, "OnKey", KeyCode.Escape); } UICamera.currentTouch = null; }
void Awake() { myCamera = GetComponent<UICamera>(); originalLayerMask = myCamera.eventReceiverMask; }
// Token: 0x06000303 RID: 771 RVA: 0x00024538 File Offset: 0x00022738 public void ProcessTouch(bool pressed, bool unpressed) { bool flag = UICamera.currentTouch == UICamera.mMouse[0]; float num = (!flag) ? this.touchDragThreshold : this.mouseDragThreshold; float num2 = (!flag) ? this.touchClickThreshold : this.mouseClickThreshold; if (pressed) { if (this.mTooltip != null) { this.ShowTooltip(false); } UICamera.currentTouch.pressStarted = true; UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", false); UICamera.currentTouch.pressed = UICamera.currentTouch.current; UICamera.currentTouch.dragged = UICamera.currentTouch.current; UICamera.currentTouch.clickNotification = UICamera.ClickNotification.Always; UICamera.currentTouch.totalDelta = Vector2.zero; UICamera.currentTouch.dragStarted = false; UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", true); if (UICamera.currentTouch.pressed != UICamera.mSel) { if (this.mTooltip != null) { this.ShowTooltip(false); } UICamera.selectedObject = null; } } else { if (UICamera.currentTouch.clickNotification != UICamera.ClickNotification.None && !this.stickyPress && !unpressed && UICamera.currentTouch.pressStarted && UICamera.currentTouch.pressed != UICamera.hoveredObject) { UICamera.isDragging = true; UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", false); UICamera.currentTouch.pressed = UICamera.hoveredObject; UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", true); UICamera.isDragging = false; } if (UICamera.currentTouch.pressed != null) { float magnitude = UICamera.currentTouch.delta.magnitude; if (magnitude != 0f) { UICamera.currentTouch.totalDelta += UICamera.currentTouch.delta; magnitude = UICamera.currentTouch.totalDelta.magnitude; if (!UICamera.currentTouch.dragStarted && num < magnitude) { UICamera.currentTouch.dragStarted = true; UICamera.currentTouch.delta = UICamera.currentTouch.totalDelta; } if (UICamera.currentTouch.dragStarted) { if (this.mTooltip != null) { this.ShowTooltip(false); } UICamera.isDragging = true; bool flag2 = UICamera.currentTouch.clickNotification == UICamera.ClickNotification.None; UICamera.Notify(UICamera.currentTouch.dragged, "OnDrag", UICamera.currentTouch.delta); UICamera.isDragging = false; if (flag2) { UICamera.currentTouch.clickNotification = UICamera.ClickNotification.None; } else if (UICamera.currentTouch.clickNotification == UICamera.ClickNotification.BasedOnDelta && num2 < magnitude) { UICamera.currentTouch.clickNotification = UICamera.ClickNotification.None; } } } } } if (unpressed) { UICamera.currentTouch.pressStarted = false; if (this.mTooltip != null) { this.ShowTooltip(false); } if (UICamera.currentTouch.pressed != null) { UICamera.Notify(UICamera.currentTouch.pressed, "OnPress", false); if (this.useMouse && UICamera.currentTouch.pressed == UICamera.mHover) { UICamera.Notify(UICamera.currentTouch.pressed, "OnHover", true); } if (UICamera.currentTouch.dragged == UICamera.currentTouch.current || (UICamera.currentTouch.clickNotification != UICamera.ClickNotification.None && UICamera.currentTouch.totalDelta.magnitude < num)) { if (UICamera.currentTouch.pressed != UICamera.mSel) { UICamera.mSel = UICamera.currentTouch.pressed; UICamera.Notify(UICamera.currentTouch.pressed, "OnSelect", true); } else { UICamera.mSel = UICamera.currentTouch.pressed; } if (UICamera.currentTouch.clickNotification != UICamera.ClickNotification.None) { float realtimeSinceStartup = Time.realtimeSinceStartup; UICamera.Notify(UICamera.currentTouch.pressed, "OnClick", null); if (UICamera.currentTouch.clickTime + 0.35f > realtimeSinceStartup) { UICamera.Notify(UICamera.currentTouch.pressed, "OnDoubleClick", null); } UICamera.currentTouch.clickTime = realtimeSinceStartup; } } else { UICamera.Notify(UICamera.currentTouch.current, "OnDrop", UICamera.currentTouch.dragged); } } UICamera.currentTouch.dragStarted = false; UICamera.currentTouch.pressed = null; UICamera.currentTouch.dragged = null; } }
public void Start() { if(CNetwork.IsServer) { // Offset its position gameObject.GetComponent<CNetworkView>().SetPosition(new Vector3(0.0f, 0.0f, s_UIOffset)); gameObject.GetComponent<CNetworkView>().SetEulerAngles(Quaternion.identity.eulerAngles); if(m_DUICamera3D != null) { m_Cached3DCamera = m_DUICamera3D.GetComponent<UICamera>(); m_Cached3DCamera.m_IsDUI = true; } if(m_DUICamera2D != null) { m_Cached2DCamera = m_DUICamera2D.GetComponent<UICamera>(); m_Cached2DCamera.m_IsDUI = true; } // Increment the offset s_UIOffset += 10.0f; } }
public void Show() { if (base.enabled && NGUITools.GetActive(base.gameObject) && mChild == null && atlas != null && isValid && items.Count > 0) { mLabelList.Clear(); if (mPanel == null) { mPanel = UIPanel.Find(base.transform); if (mPanel == null) { return; } } handleEvents = true; Transform transform = base.transform; Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(transform.parent, transform); mChild = new GameObject("Drop-down List"); mChild.layer = base.gameObject.layer; Transform transform2 = mChild.transform; transform2.parent = transform.parent; transform2.localPosition = bounds.min; transform2.localRotation = Quaternion.identity; transform2.localScale = Vector3.one; mBackground = NGUITools.AddSprite(mChild, atlas, backgroundSprite); mBackground.pivot = UIWidget.Pivot.TopLeft; mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject); mBackground.color = backgroundColor; Vector4 border = mBackground.border; mBgBorder = border.y; mBackground.cachedTransform.localPosition = new Vector3(0f, border.y, 0f); mHighlight = NGUITools.AddSprite(mChild, atlas, highlightSprite); mHighlight.pivot = UIWidget.Pivot.TopLeft; mHighlight.color = highlightColor; UISpriteData atlasSprite = mHighlight.GetAtlasSprite(); if (atlasSprite != null) { float num = (float)atlasSprite.borderTop; float num2 = (float)activeFontSize; float activeFontScale = this.activeFontScale; float num3 = num2 * activeFontScale; float num4 = 0f; float num5 = 0f - padding.y; List <UILabel> list = new List <UILabel>(); if (!items.Contains(mSelectedItem)) { mSelectedItem = null; } int i = 0; for (int count = items.Count; i < count; i++) { string text = items[i]; UILabel uILabel = NGUITools.AddWidget <UILabel>(mChild); uILabel.name = i.ToString(); uILabel.pivot = UIWidget.Pivot.TopLeft; uILabel.bitmapFont = bitmapFont; uILabel.trueTypeFont = trueTypeFont; uILabel.fontSize = fontSize; uILabel.fontStyle = fontStyle; uILabel.text = ((!isLocalized) ? text : Localization.Get(text)); uILabel.color = textColor; Transform cachedTransform = uILabel.cachedTransform; float num6 = border.x + padding.x; Vector2 pivotOffset = uILabel.pivotOffset; cachedTransform.localPosition = new Vector3(num6 - pivotOffset.x, num5, -1f); uILabel.overflowMethod = UILabel.Overflow.ResizeFreely; uILabel.alignment = alignment; list.Add(uILabel); num5 -= num3; num5 -= padding.y; float a = num4; Vector2 printedSize = uILabel.printedSize; num4 = Mathf.Max(a, printedSize.x); UIEventListener uIEventListener = UIEventListener.Get(uILabel.gameObject); uIEventListener.onHover = OnItemHover; uIEventListener.onPress = OnItemPress; uIEventListener.onClick = OnItemClick; uIEventListener.parameter = text; if (mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(mSelectedItem))) { Highlight(uILabel, instant: true); } mLabelList.Add(uILabel); } float a2 = num4; Vector3 size = bounds.size; num4 = Mathf.Max(a2, size.x * activeFontScale - (border.x + padding.x) * 2f); float num7 = num4; Vector3 vector = new Vector3(num7 * 0.5f, (0f - num2) * 0.5f, 0f); Vector3 vector2 = new Vector3(num7, num3 + padding.y, 1f); int j = 0; for (int count2 = list.Count; j < count2; j++) { UILabel uILabel2 = list[j]; NGUITools.AddWidgetCollider(uILabel2.gameObject); uILabel2.autoResizeBoxCollider = false; BoxCollider component = uILabel2.GetComponent <BoxCollider>(); if (component != null) { Vector3 center = component.center; vector.z = center.z; component.center = vector; component.size = vector2; } else { BoxCollider2D component2 = uILabel2.GetComponent <BoxCollider2D>(); component2.offset = vector; component2.size = vector2; } } int width = Mathf.RoundToInt(num4); num4 += (border.x + padding.x) * 2f; num5 -= border.y; mBackground.width = Mathf.RoundToInt(num4); mBackground.height = Mathf.RoundToInt(0f - num5 + border.y); int k = 0; for (int count3 = list.Count; k < count3; k++) { UILabel uILabel3 = list[k]; uILabel3.overflowMethod = UILabel.Overflow.ShrinkContent; uILabel3.width = width; } float num8 = 2f * atlas.pixelSize; float f = num4 - (border.x + padding.x) * 2f + (float)atlasSprite.borderLeft * num8; float f2 = num3 + num * num8; mHighlight.width = Mathf.RoundToInt(f); mHighlight.height = Mathf.RoundToInt(f2); bool flag = position == Position.Above; if (position == Position.Auto) { UICamera uICamera = UICamera.FindCameraForLayer(base.gameObject.layer); if (uICamera != null) { Vector3 vector3 = uICamera.cachedCamera.WorldToViewportPoint(transform.position); flag = (vector3.y < 0.5f); } } if (isAnimated) { float bottom = num5 + num3; Animate(mHighlight, flag, bottom); int l = 0; for (int count4 = list.Count; l < count4; l++) { Animate(list[l], flag, bottom); } AnimateColor(mBackground); AnimateScale(mBackground, flag, bottom); } if (flag) { Transform transform3 = transform2; Vector3 min = bounds.min; float x = min.x; Vector3 max = bounds.max; float y = max.y - num5 - border.y; Vector3 min2 = bounds.min; transform3.localPosition = new Vector3(x, y, min2.z); } } } else { OnSelect(isSelected: false); } }
// Use this for initialization void Start() { cam_Comp = GetComponent<UICamera>(); }
/// <summary> /// Selection change is delayed on purpose. This way selection changes during event processing won't cause /// the newly selected widget to continue processing when it is it's turn. Example: pressing 'tab' on one /// button selects the next button, and then it also processes its 'tab' in turn, selecting the next one. /// </summary> System.Collections.IEnumerator ChangeSelection (GameObject go) { yield return new WaitForEndOfFrame(); mCurrentSelection = go; mNextSelection = null; if (mCurrentSelection != null) { current = this; currentCamera = mCam; if (useController || useKeyboard) Highlight(mCurrentSelection, true); Notify(mCurrentSelection, "OnSelect", true); current = null; } }
protected virtual void Update() { if (!this.isSelected || this.mSelectTime == Time.frameCount) { return; } if (this.mDoInit) { this.Init(); } if (this.mSelectMe != -1 && this.mSelectMe != Time.frameCount) { this.mSelectMe = -1; this.mSelectionEnd = ((!string.IsNullOrEmpty(this.mValue)) ? this.mValue.Length : 0); UIInput.mDrawStart = 0; this.mSelectionStart = ((!this.selectAllTextOnFocus) ? this.mSelectionEnd : 0); this.label.color = this.activeTextColor; Vector2 compositionCursorPos = (!(UICamera.current != null) || !(UICamera.current.cachedCamera != null)) ? this.label.worldCorners[0] : UICamera.current.cachedCamera.WorldToScreenPoint(this.label.worldCorners[0]); compositionCursorPos.y = (float)Screen.height - compositionCursorPos.y; Input.imeCompositionMode = IMECompositionMode.On; Input.compositionCursorPos = compositionCursorPos; this.UpdateLabel(); if (string.IsNullOrEmpty(Input.inputString)) { return; } } string compositionString = Input.compositionString; if (string.IsNullOrEmpty(compositionString) && !string.IsNullOrEmpty(Input.inputString)) { string inputString = Input.inputString; for (int i = 0; i < inputString.Length; i++) { char c = inputString[i]; if (c >= ' ') { if (c != '') { if (c != '') { if (c != '') { if (c != '') { this.Insert(c.ToString()); } } } } } } } if (UIInput.mLastIME != compositionString) { this.mSelectionEnd = ((!string.IsNullOrEmpty(compositionString)) ? (this.mValue.Length + compositionString.Length) : this.mSelectionStart); UIInput.mLastIME = compositionString; this.UpdateLabel(); this.ExecuteOnChange(); } if (this.mCaret != null && this.mNextBlink < RealTime.time) { this.mNextBlink = RealTime.time + 0.5f; this.mCaret.enabled = !this.mCaret.enabled; } if (this.isSelected && this.mLastAlpha != this.label.finalAlpha) { this.UpdateLabel(); } if (this.mCam == null) { this.mCam = UICamera.FindCameraForLayer(base.gameObject.layer); } if (this.mCam != null) { if (UICamera.GetKeyDown(this.mCam.submitKey0)) { bool flag = this.onReturnKey == UIInput.OnReturnKey.NewLine || (this.onReturnKey == UIInput.OnReturnKey.Default && this.label.multiLine && !Input.GetKey(KeyCode.LeftControl) && !Input.GetKey(KeyCode.RightControl) && this.label.overflowMethod != UILabel.Overflow.ClampContent && this.validation == UIInput.Validation.None); if (flag) { this.Insert("\n"); } else { if (UICamera.controller.current != null) { UICamera.controller.clickNotification = UICamera.ClickNotification.None; } UICamera.currentKey = this.mCam.submitKey0; this.Submit(); } } if (UICamera.GetKeyDown(this.mCam.submitKey1)) { bool flag2 = this.onReturnKey == UIInput.OnReturnKey.NewLine || (this.onReturnKey == UIInput.OnReturnKey.Default && this.label.multiLine && !Input.GetKey(KeyCode.LeftControl) && !Input.GetKey(KeyCode.RightControl) && this.label.overflowMethod != UILabel.Overflow.ClampContent && this.validation == UIInput.Validation.None); if (flag2) { this.Insert("\n"); } else { if (UICamera.controller.current != null) { UICamera.controller.clickNotification = UICamera.ClickNotification.None; } UICamera.currentKey = this.mCam.submitKey1; this.Submit(); } } if (!this.mCam.useKeyboard && UICamera.GetKeyUp(KeyCode.Tab)) { this.OnKey(KeyCode.Tab); } } }
/// <summary> /// Update the text based on input. /// </summary> protected virtual void Update () { #if UNITY_EDITOR if (!Application.isPlaying) return; #endif if (!isSelected || mSelectTime == Time.frameCount) return; if (mDoInit) Init(); #if MOBILE // Wait for the keyboard to open. Apparently mKeyboard.active will return 'false' for a while in some cases. if (mWaitForKeyboard) { if (mKeyboard != null && !mKeyboard.active) return; mWaitForKeyboard = false; } #endif // Unity has issues bringing up the keyboard properly if it's in "hideInput" mode and you happen // to select one input in the same Update as de-selecting another. if (mSelectMe != -1 && mSelectMe != Time.frameCount) { mSelectMe = -1; mSelectionEnd = string.IsNullOrEmpty(mValue) ? 0 : mValue.Length; mDrawStart = 0; mSelectionStart = selectAllTextOnFocus ? 0 : mSelectionEnd; label.color = activeTextColor; #if MOBILE RuntimePlatform pf = Application.platform; if (pf == RuntimePlatform.IPhonePlayer || pf == RuntimePlatform.Android || pf == RuntimePlatform.WP8Player #if UNITY_4_3 || pf == RuntimePlatform.BB10Player #else || pf == RuntimePlatform.BlackBerryPlayer || pf == RuntimePlatform.MetroPlayerARM || pf == RuntimePlatform.MetroPlayerX64 || pf == RuntimePlatform.MetroPlayerX86 #endif ) { string val; TouchScreenKeyboardType kt; if (inputShouldBeHidden) { TouchScreenKeyboard.hideInput = true; kt = (TouchScreenKeyboardType)((int)keyboardType); #if UNITY_METRO val = ""; #else val = "|"; #endif } else if (inputType == InputType.Password) { TouchScreenKeyboard.hideInput = false; kt = TouchScreenKeyboardType.Default; val = mValue; mSelectionStart = mSelectionEnd; } else { TouchScreenKeyboard.hideInput = false; kt = (TouchScreenKeyboardType)((int)keyboardType); val = mValue; mSelectionStart = mSelectionEnd; } mWaitForKeyboard = true; mKeyboard = (inputType == InputType.Password) ? TouchScreenKeyboard.Open(val, kt, false, false, true) : TouchScreenKeyboard.Open(val, kt, !inputShouldBeHidden && inputType == InputType.AutoCorrect, label.multiLine && !hideInput, false, false, defaultText); #if UNITY_METRO mKeyboard.active = true; #endif } else #endif // MOBILE { Vector2 pos = (UICamera.current != null && UICamera.current.cachedCamera != null) ? UICamera.current.cachedCamera.WorldToScreenPoint(label.worldCorners[0]) : label.worldCorners[0]; pos.y = Screen.height - pos.y; Input.imeCompositionMode = IMECompositionMode.On; Input.compositionCursorPos = pos; } UpdateLabel(); if (string.IsNullOrEmpty(Input.inputString)) return; } #if MOBILE if (mKeyboard != null) { #if UNITY_METRO string text = Input.inputString; if (!string.IsNullOrEmpty(text)) Insert(text); #else string text = (mKeyboard.done || !mKeyboard.active) ? mCached : mKeyboard.text; if (inputShouldBeHidden) { if (text != "|") { if (!string.IsNullOrEmpty(text)) { Insert(text.Substring(1)); } else DoBackspace(); mKeyboard.text = "|"; } } else if (mCached != text) { mCached = text; if (!mKeyboard.done && mKeyboard.active) value = text; } #endif // UNITY_METRO if (mKeyboard.done || !mKeyboard.active) { if (!mKeyboard.wasCanceled) Submit(); mKeyboard = null; isSelected = false; mCached = ""; } } else #endif // MOBILE { string ime = Input.compositionString; // There seems to be an inconsistency between IME on Windows, and IME on OSX. // On Windows, Input.inputString is always empty while IME is active. On the OSX it is not. if (string.IsNullOrEmpty(ime) && !string.IsNullOrEmpty(Input.inputString)) { // Process input ignoring non-printable characters as they are not consistent. // Windows has them, OSX may not. They get handled inside OnGUI() instead. string s = Input.inputString; for (int i = 0; i < s.Length; ++i) { char ch = s[i]; if (ch < ' ') continue; // OSX inserts these characters for arrow keys if (ch == '\uF700') continue; if (ch == '\uF701') continue; if (ch == '\uF702') continue; if (ch == '\uF703') continue; Insert(ch.ToString()); } } // Append IME composition if (mLastIME != ime) { mSelectionEnd = string.IsNullOrEmpty(ime) ? mSelectionStart : mValue.Length + ime.Length; mLastIME = ime; UpdateLabel(); ExecuteOnChange(); } } // Blink the caret if (mCaret != null && mNextBlink < RealTime.time) { mNextBlink = RealTime.time + 0.5f; mCaret.enabled = !mCaret.enabled; } // If the label's final alpha changes, we need to update the drawn geometry, // or the highlight widgets (which have their geometry set manually) won't update. if (isSelected && mLastAlpha != label.finalAlpha) UpdateLabel(); // Cache the camera if (mCam == null) mCam = UICamera.FindCameraForLayer(gameObject.layer); // Having this in OnGUI causes issues because Input.inputString gets updated *after* OnGUI, apparently... if (mCam != null) { if (UICamera.GetKeyDown(mCam.submitKey0)) { bool newLine = (onReturnKey == OnReturnKey.NewLine) || (onReturnKey == OnReturnKey.Default && label.multiLine && !Input.GetKey(KeyCode.LeftControl) && !Input.GetKey(KeyCode.RightControl) && label.overflowMethod != UILabel.Overflow.ClampContent && validation == Validation.None); if (newLine) { Insert("\n"); } else { if (UICamera.controller.current != null) UICamera.controller.clickNotification = UICamera.ClickNotification.None; UICamera.currentKey = mCam.submitKey0; Submit(); } } if (UICamera.GetKeyDown(mCam.submitKey1)) { bool newLine = (onReturnKey == OnReturnKey.NewLine) || (onReturnKey == OnReturnKey.Default && label.multiLine && !Input.GetKey(KeyCode.LeftControl) && !Input.GetKey(KeyCode.RightControl) && label.overflowMethod != UILabel.Overflow.ClampContent && validation == Validation.None); if (newLine) { Insert("\n"); } else { if (UICamera.controller.current != null) UICamera.controller.clickNotification = UICamera.ClickNotification.None; UICamera.currentKey = mCam.submitKey1; Submit(); } } if (!mCam.useKeyboard && UICamera.GetKeyUp(KeyCode.Tab)) OnKey(KeyCode.Tab); } }
protected virtual void OnBindingPress(bool pressed) { UICamera.Notify(base.gameObject, "OnPress", pressed); }
/// <summary> /// Selection change is delayed on purpose. This way selection changes during event processing won't cause /// the newly selected widget to continue processing when it is it's turn. Example: pressing 'tab' on one /// button selects the next button, and then it also processes its 'tab' in turn, selecting the next one. /// </summary> System.Collections.IEnumerator ChangeSelection () { yield return new WaitForEndOfFrame(); Notify(mCurrentSelection, "OnSelect", false); mCurrentSelection = mNextSelection; mNextSelection = null; if (mCurrentSelection != null) { current = this; currentCamera = mCam; UICamera.currentScheme = mNextScheme; inputHasFocus = (mCurrentSelection.GetComponent<UIInput>() != null); Notify(mCurrentSelection, "OnSelect", true); current = null; } else inputHasFocus = false; }
/// <summary> /// Change the selection. /// </summary> static protected void SetSelection (GameObject go, ControlScheme scheme) { if (mNextSelection != null) { mNextSelection = go; } else if (mCurrentSelection != go) { if (mCurrentSelection != null) { UICamera uicam = FindCameraForLayer(mCurrentSelection.layer); if (uicam != null) { current = uicam; currentCamera = uicam.mCam; UICamera.currentScheme = scheme; Notify(mCurrentSelection, "OnSelect", false); current = null; } } mCurrentSelection = null; mNextSelection = go; mNextScheme = scheme; if (UICamera.list.size > 0) { UICamera cam = (mNextSelection != null) ? FindCameraForLayer(mNextSelection.layer) : UICamera.list[0]; if (cam != null) cam.StartCoroutine(cam.ChangeSelection()); } } }
/// <summary> /// Display the drop-down list when the game object gets clicked on. /// </summary> void OnClick() { if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0) { mLabelList.Clear(); // Automatically locate the panel responsible for this object if (mPanel == null) { mPanel = UIPanel.Find(transform); if (mPanel == null) { return; } } // Disable the navigation script handleEvents = true; // Calculate the dimensions of the object triggering the popup list so we can position it below it Transform myTrans = transform; Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans); // Create the root object for the list mChild = new GameObject("Drop-down List"); mChild.layer = gameObject.layer; Transform t = mChild.transform; t.parent = myTrans.parent; t.localPosition = bounds.min; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; // Add a sprite for the background mBackground = NGUITools.AddSprite(mChild, atlas, backgroundSprite); mBackground.pivot = UIWidget.Pivot.TopLeft; mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject); mBackground.color = backgroundColor; // We need to know the size of the background sprite for padding purposes Vector4 bgPadding = mBackground.border; mBgBorder = bgPadding.y; mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f); // Add a sprite used for the selection mHighlight = NGUITools.AddSprite(mChild, atlas, highlightSprite); mHighlight.pivot = UIWidget.Pivot.TopLeft; mHighlight.color = highlightColor; UISpriteData hlsp = mHighlight.GetAtlasSprite(); if (hlsp == null) { return; } float hlspHeight = hlsp.borderTop; float pixelSize = (bitmapFont != null) ? bitmapFont.pixelSize : 1f; float fontHeight = activeFontSize * pixelSize; float dynScale = activeFontScale; float labelHeight = fontHeight * dynScale; float x = 0f, y = -padding.y; int labelFontSize = (bitmapFont != null) ? bitmapFont.defaultSize : fontSize; List <UILabel> labels = new List <UILabel>(); // Run through all items and create labels for each one for (int i = 0, imax = items.Count; i < imax; ++i) { string s = items[i]; UILabel lbl = NGUITools.AddWidget <UILabel>(mChild); lbl.pivot = UIWidget.Pivot.TopLeft; lbl.bitmapFont = bitmapFont; lbl.trueTypeFont = trueTypeFont; lbl.fontSize = labelFontSize; lbl.fontStyle = fontStyle; lbl.text = isLocalized ? Localization.Get(s) : s; lbl.color = textColor; lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x, y, -1f); lbl.overflowMethod = UILabel.Overflow.ResizeFreely; lbl.MakePixelPerfect(); if (dynScale != 1f) { lbl.cachedTransform.localScale = Vector3.one * dynScale; } labels.Add(lbl); y -= labelHeight; y -= padding.y; x = Mathf.Max(x, lbl.printedSize.x); // Add an event listener UIEventListener listener = UIEventListener.Get(lbl.gameObject); listener.onHover = OnItemHover; listener.onPress = OnItemPress; listener.parameter = s; // Move the selection here if this is the right label if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem))) { Highlight(lbl, true); } // Add this label to the list mLabelList.Add(lbl); } // The triggering widget's width should be the minimum allowed width x = Mathf.Max(x, bounds.size.x * dynScale - (bgPadding.x + padding.x) * 2f); float cx = x / dynScale; Vector3 bcCenter = new Vector3(cx * 0.5f, -fontHeight * 0.5f, 0f); Vector3 bcSize = new Vector3(cx, (labelHeight + padding.y) / dynScale, 1f); // Run through all labels and add colliders for (int i = 0, imax = labels.Count; i < imax; ++i) { UILabel lbl = labels[i]; BoxCollider bc = NGUITools.AddWidgetCollider(lbl.gameObject); bcCenter.z = bc.center.z; bc.center = bcCenter; bc.size = bcSize; } x += (bgPadding.x + padding.x) * 2f; y -= bgPadding.y; // Scale the background sprite to envelop the entire set of items mBackground.width = Mathf.RoundToInt(x); mBackground.height = Mathf.RoundToInt(-y + bgPadding.y); // Scale the highlight sprite to envelop a single item float scaleFactor = 2f * atlas.pixelSize; float w = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor; float h = labelHeight + hlspHeight * scaleFactor; mHighlight.width = Mathf.RoundToInt(w); mHighlight.height = Mathf.RoundToInt(h); bool placeAbove = (position == Position.Above); if (position == Position.Auto) { UICamera cam = UICamera.FindCameraForLayer(gameObject.layer); if (cam != null) { Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(myTrans.position); placeAbove = (viewPos.y < 0.5f); } } // If the list should be animated, let's animate it by expanding it if (isAnimated) { float bottom = y + labelHeight; Animate(mHighlight, placeAbove, bottom); for (int i = 0, imax = labels.Count; i < imax; ++i) { Animate(labels[i], placeAbove, bottom); } AnimateColor(mBackground); AnimateScale(mBackground, placeAbove, bottom); } // If we need to place the popup list above the item, we need to reposition everything by the size of the list if (placeAbove) { t.localPosition = new Vector3(bounds.min.x, bounds.max.y - y - bgPadding.y, bounds.min.z); } } else { OnSelect(false); } }
// Token: 0x060007A0 RID: 1952 RVA: 0x0003EDB4 File Offset: 0x0003CFB4 protected virtual void Update() { if (!this.isSelected || this.mSelectTime == Time.frameCount) { return; } if (this.mDoInit) { this.Init(); } if (this.mSelectMe != -1 && this.mSelectMe != Time.frameCount) { this.mSelectMe = -1; this.mSelectionEnd = (string.IsNullOrEmpty(this.mValue) ? 0 : this.mValue.Length); UIInput.mDrawStart = 0; this.mSelectionStart = (this.selectAllTextOnFocus ? 0 : this.mSelectionEnd); this.label.color = this.activeTextColor; Vector2 vector = (UICamera.current != null && UICamera.current.cachedCamera != null) ? UICamera.current.cachedCamera.WorldToScreenPoint(this.label.worldCorners[0]) : this.label.worldCorners[0]; vector.y = (float)Screen.height - vector.y; Input.imeCompositionMode = IMECompositionMode.On; Input.compositionCursorPos = vector; this.UpdateLabel(); if (string.IsNullOrEmpty(Input.inputString)) { return; } } string compositionString = Input.compositionString; if (string.IsNullOrEmpty(compositionString) && !string.IsNullOrEmpty(Input.inputString)) { foreach (char c in Input.inputString) { if (c >= ' ' && c != '' && c != '' && c != '' && c != '' && c != '') { this.Insert(c.ToString()); } } } if (UIInput.mLastIME != compositionString) { this.mSelectionEnd = (string.IsNullOrEmpty(compositionString) ? this.mSelectionStart : (this.mValue.Length + compositionString.Length)); UIInput.mLastIME = compositionString; this.UpdateLabel(); this.ExecuteOnChange(); } if (this.mCaret != null && this.mNextBlink < RealTime.time) { this.mNextBlink = RealTime.time + 0.5f; this.mCaret.enabled = !this.mCaret.enabled; } if (this.isSelected && this.mLastAlpha != this.label.finalAlpha) { this.UpdateLabel(); } if (this.mCam == null) { this.mCam = UICamera.FindCameraForLayer(base.gameObject.layer); } if (this.mCam != null) { bool flag = false; if (this.label.multiLine) { bool flag2 = Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); if (this.onReturnKey == UIInput.OnReturnKey.Submit) { flag = flag2; } else { flag = !flag2; } } if (UICamera.GetKeyDown(this.mCam.submitKey0) || (this.mCam.submitKey0 == KeyCode.Return && UICamera.GetKeyDown(KeyCode.KeypadEnter))) { if (flag) { this.Insert("\n"); } else { if (UICamera.controller.current != null) { UICamera.controller.clickNotification = UICamera.ClickNotification.None; } UICamera.currentKey = this.mCam.submitKey0; this.Submit(); } } if (UICamera.GetKeyDown(this.mCam.submitKey1) || (this.mCam.submitKey1 == KeyCode.Return && UICamera.GetKeyDown(KeyCode.KeypadEnter))) { if (flag) { this.Insert("\n"); } else { if (UICamera.controller.current != null) { UICamera.controller.clickNotification = UICamera.ClickNotification.None; } UICamera.currentKey = this.mCam.submitKey1; this.Submit(); } } if (!this.mCam.useKeyboard && UICamera.GetKeyUp(KeyCode.Tab)) { this.OnKey(KeyCode.Tab); } } }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { // Only the first UI layer should be processing events if (!Application.isPlaying || !handlesEvents) return; current = this; int w = Screen.width; int h = Screen.height; if (w != mWidth || h != mHeight) { mWidth = w; mHeight = h; if (onScreenResize != null) onScreenResize(); } if (useTouch) { // Process touch events first ProcessTouches (); // If we want to process mouse events, only do so if there are no active touch events, // otherwise there is going to be event duplication as Unity treats touch events as mouse events. if (useMouse && Input.touchCount == 0) ProcessMouse(); } else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mCurrentSelection != null) { if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) { currentKey = cancelKey0; selectedObject = null; } else if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)) { currentKey = cancelKey1; selectedObject = null; } } // Forward the input to the selected object if (mCurrentSelection != null) { string input = Input.inputString; // Adding support for some macs only having the "Delete" key instead of "Backspace" if (useKeyboard && Input.GetKeyDown(KeyCode.Delete)) input += "\b"; if (input.Length > 0) { if (!stickyTooltip && mTooltip != null) ShowTooltip(false); Notify(mCurrentSelection, "OnInput", input); } } else inputHasFocus = false; // Update the keyboard and joystick events if (mCurrentSelection != null) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = Input.GetAxis(scrollAxisName); if (scroll != 0f) Notify(mHover, "OnScroll", scroll); if (showTooltips && mTooltipTime != 0f && (mTooltipTime < RealTime.time || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; }
/// <summary> /// Convenience function that figures out the panel's correct change flag by searching the parents. /// </summary> int GetChangeFlag(UINode start) { int flag = start.changeFlag; if (flag == -1) { Transform trans = start.trans.parent; UINode sub; // Keep going until we find a set flag for (;;) { // Check the parent's flag #if USE_SIMPLE_DICTIONARY if (trans != null && mChildren.TryGetValue(trans, out sub)) { #else if (trans != null && mChildren.Contains(trans)) { sub = (UINode)mChildren[trans]; #endif flag = sub.changeFlag; trans = trans.parent; // If the flag hasn't been set either, add this child to the hierarchy if (flag == -1) { mHierarchy.Add(sub); } else { break; } } else { flag = 0; break; } } // Update the parent flags for (int i = 0, imax = mHierarchy.size; i < imax; ++i) { UINode pc = mHierarchy.buffer[i]; pc.changeFlag = flag; } mHierarchy.Clear(); } return(flag); } /// <summary> /// Run through all managed transforms and see if they've changed. /// </summary> void UpdateTransforms() { bool transformsChanged = false; bool shouldCull = false; #if UNITY_EDITOR shouldCull = (clipping != UIDrawCall.Clipping.None) && (!Application.isPlaying || (cullWhileDragging || mUpdateTime > mCullTime)); if (!Application.isPlaying || !widgetsAreStatic || mWidgetsAdded || shouldCull != mCulled) #else shouldCull = (clipping != UIDrawCall.Clipping.None) && (mUpdateTime > mCullTime); if (!widgetsAreStatic || mWidgetsAdded || shouldCull != mCulled) #endif { #if USE_SIMPLE_DICTIONARY foreach (KeyValuePair <Transform, UINode> child in mChildren) { UINode node = child.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode node = (UINode)mChildren[i]; #endif if (node.trans == null) { mRemoved.Add(node.trans); continue; } if (node.HasChanged()) { node.changeFlag = 1; transformsChanged = true; #if UNITY_EDITOR Vector3 s = node.trans.lossyScale; float min = Mathf.Abs(Mathf.Min(s.x, s.y)); if (min == 0f) { Debug.LogError("Scale of 0 is invalid! Zero cannot be divided by, which causes problems. Use a small value instead, such as 0.01\n" + node.trans.lossyScale, node.trans); } #endif } else { node.changeFlag = -1; } } // Clean up the deleted transforms for (int i = 0, imax = mRemoved.Count; i < imax; ++i) { mChildren.Remove(mRemoved[i]); } mRemoved.Clear(); } // If the children weren't culled but should be, check their visibility if (!mCulled && shouldCull) { mCheckVisibility = true; } // If something has changed, propagate the changes *down* the tree hierarchy (to children). // An alternative (but slower) approach would be to do a pc.trans.GetComponentsInChildren<UIWidget>() // in the loop above, and mark each one as dirty. if (mCheckVisibility || transformsChanged || mRebuildAll) { #if USE_SIMPLE_DICTIONARY foreach (KeyValuePair <Transform, UINode> child in mChildren) { UINode pc = child.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode pc = (UINode)mChildren[i]; #endif if (pc.widget != null) { int visibleFlag = 1; // No sense in checking the visibility if we're not culling anything (as the visibility is always 'true') if (shouldCull || transformsChanged) { // If the change flag has not yet been determined... if (pc.changeFlag == -1) { pc.changeFlag = GetChangeFlag(pc); } // Is the widget visible? if (shouldCull) { visibleFlag = (mCheckVisibility || pc.changeFlag == 1) ? (IsVisible(pc.widget) ? 1 : 0) : pc.visibleFlag; } } // If visibility changed, mark the node as changed as well if (pc.visibleFlag != visibleFlag) { pc.changeFlag = 1; } // If the node has changed and the widget is visible (or was visible before) if (pc.changeFlag == 1 && (visibleFlag == 1 || pc.visibleFlag != 0)) { // Update the visibility flag pc.visibleFlag = visibleFlag; Material mat = pc.widget.material; // Add this material to the list of changed materials if (!mChanged.Contains(mat)) { mChanged.Add(mat); } } } } } mCulled = shouldCull; mCheckVisibility = false; mWidgetsAdded = false; } /// <summary> /// Update all widgets and rebuild their geometry if necessary. /// </summary> void UpdateWidgets() { #if USE_SIMPLE_DICTIONARY foreach (KeyValuePair <Transform, UINode> c in mChildren) { UINode pc = c.Value; #else for (int i = 0, imax = mChildren.Count; i < imax; ++i) { UINode pc = (UINode)mChildren[i]; #endif UIWidget w = pc.widget; // If the widget is visible, update it if (pc.visibleFlag == 1 && w != null && w.UpdateGeometry(this, ref worldToLocal, (pc.changeFlag == 1), generateNormals)) { // We will need to refill this buffer if (!mChanged.Contains(w.material)) { mChanged.Add(w.material); } } pc.changeFlag = 0; } } #endif /// <summary> /// Update the clipping rect in the shaders and draw calls' positions. /// </summary> public void UpdateDrawcalls() { Vector4 range = Vector4.zero; if (mClipping != UIDrawCall.Clipping.None) { range = new Vector4(mClipRange.x, mClipRange.y, mClipRange.z * 0.5f, mClipRange.w * 0.5f); } if (range.z == 0f) { range.z = Screen.width * 0.5f; } if (range.w == 0f) { range.w = Screen.height * 0.5f; } RuntimePlatform platform = Application.platform; if (platform == RuntimePlatform.WindowsPlayer || platform == RuntimePlatform.WindowsWebPlayer || platform == RuntimePlatform.WindowsEditor) { range.x -= 0.5f; range.y += 0.5f; } Transform t = cachedTransform; UIDrawCall dc; Transform dt; for (int i = 0, imax = mDrawCalls.size; i < imax; ++i) { dc = mDrawCalls.buffer[i]; dc.clipping = mClipping; dc.clipRange = range; dc.clipSoftness = mClipSoftness; dc.depthPass = depthPass && mClipping == UIDrawCall.Clipping.None; // Set the draw call's transform to match the panel's. // Note that parenting directly to the panel causes unity to crash as soon as you hit Play. dt = dc.transform; dt.position = t.position; dt.rotation = t.rotation; dt.localScale = t.lossyScale; } } /// <summary> /// Set the draw call's geometry responsible for the specified material. /// </summary> void Fill(Material mat) { // Fill the buffers for the specified material for (int i = 0; i < mWidgets.size;) { UIWidget w = mWidgets.buffer[i]; if (w == null) { mWidgets.RemoveAt(i); continue; } #if OLD_UNITY else if (w.visibleFlag == 1 && w.material == mat) #else else if (w.material == mat && w.isVisible) #endif { if (w.panel == this) { if (generateNormals) { w.WriteToBuffers(mVerts, mUvs, mCols, mNorms, mTans); } else { w.WriteToBuffers(mVerts, mUvs, mCols, null, null); } } else { mWidgets.RemoveAt(i); continue; } } ++i; } if (mVerts.size > 0) { // Rebuild the draw call's mesh UIDrawCall dc = GetDrawCall(mat, true); dc.depthPass = depthPass && mClipping == UIDrawCall.Clipping.None; dc.Set(mVerts, generateNormals ? mNorms : null, generateNormals ? mTans : null, mUvs, mCols); } else { // There is nothing to draw for this material -- eliminate the draw call UIDrawCall dc = GetDrawCall(mat, false); if (dc != null) { mDrawCalls.Remove(dc); NGUITools.DestroyImmediate(dc.gameObject); } } // Cleanup mVerts.Clear(); mNorms.Clear(); mTans.Clear(); mUvs.Clear(); mCols.Clear(); } /// <summary> /// Main update function /// </summary> void LateUpdate() { mUpdateTime = Time.realtimeSinceStartup; UpdateTransformMatrix(); #if OLD_UNITY UpdateTransforms(); #endif // Always move widgets to the panel's layer if (mLayer != cachedGameObject.layer) { mLayer = mGo.layer; UICamera uic = UICamera.FindCameraForLayer(mLayer); mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer); SetChildLayer(cachedTransform, mLayer); for (int i = 0, imax = drawCalls.size; i < imax; ++i) { mDrawCalls.buffer[i].gameObject.layer = mLayer; } } #if OLD_UNITY UpdateWidgets(); #else #if UNITY_EDITOR bool forceVisible = cullWhileDragging ? false : (clipping == UIDrawCall.Clipping.None) || (Application.isPlaying && mCullTime > mUpdateTime); #else bool forceVisible = cullWhileDragging ? false : (clipping == UIDrawCall.Clipping.None) || (mCullTime > mUpdateTime); #endif // Update all widgets for (int i = 0, imax = mWidgets.size; i < imax; ++i) { UIWidget w = mWidgets[i]; // If the widget is visible, update it if (w.UpdateGeometry(this, forceVisible)) { // We will need to refill this buffer if (!mChanged.Contains(w.material)) { mChanged.Add(w.material); } } } #endif // Inform the changed event listeners if (mChanged.size != 0 && onChange != null) { onChange(); } // If the depth has changed, we need to re-sort the widgets if (mDepthChanged) { mDepthChanged = false; mWidgets.Sort(UIWidget.CompareFunc); } // Fill the draw calls for all of the changed materials for (int i = 0, imax = mChanged.size; i < imax; ++i) { Fill(mChanged.buffer[i]); } // Update the clipping rects UpdateDrawcalls(); mChanged.Clear(); #if OLD_UNITY mRebuildAll = false; #endif #if UNITY_EDITOR mScreenSize = new Vector2(Screen.width, Screen.height); #endif }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { // Only the first UI layer should be processing events #if UNITY_EDITOR if (!Application.isPlaying || !handlesEvents) return; #else if (!handlesEvents) return; #endif current = this; // Process touch events first if (useTouch) ProcessTouches (); else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mCurrentSelection != null) { if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey0; selectedObject = null; } else if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey1; selectedObject = null; } } // If nothing is selected, input focus is lost if (mCurrentSelection == null) inputHasFocus = false; // Update the keyboard and joystick events if (mCurrentSelection != null) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = !string.IsNullOrEmpty(scrollAxisName) ? Input.GetAxis(scrollAxisName) : 0f; if (scroll != 0f) Notify(mHover, "OnScroll", scroll); if (showTooltips && mTooltipTime != 0f && (mTooltipTime < RealTime.time || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; }
/// <summary> /// Show the popup list dialog. /// </summary> public void Show() { if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0) { mLabelList.Clear(); // Automatically locate the panel responsible for this object if (mPanel == null) { mPanel = UIPanel.Find(transform); if (mPanel == null) { return; } } // Disable the navigation script handleEvents = true; // Calculate the dimensions of the object triggering the popup list so we can position it below it Transform myTrans = transform; Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans); // Create the root object for the list mChild = new GameObject("Drop-down List"); mChild.layer = gameObject.layer; Transform t = mChild.transform; t.parent = myTrans.parent; Vector3 min; Vector3 max; Vector3 pos; // Manually triggered popup list on some other game object if (openOn == OpenOn.Manual && UICamera.selectedObject != gameObject && bounds.size == Vector3.zero) { StopCoroutine("CloseIfUnselected"); min = t.parent.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(UICamera.lastTouchPosition)); max = min; t.localPosition = min; pos = t.position; StartCoroutine("CloseIfUnselected"); } else { min = bounds.min; max = bounds.max; t.localPosition = min; pos = myTrans.position; } t.localRotation = Quaternion.identity; t.localScale = Vector3.one; // Add a sprite for the background mBackground = NGUITools.AddSprite(mChild, atlas, backgroundSprite); mBackground.pivot = UIWidget.Pivot.TopLeft; mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject); mBackground.color = backgroundColor; // We need to know the size of the background sprite for padding purposes Vector4 bgPadding = mBackground.border; mBgBorder = bgPadding.y; mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f); // Add a sprite used for the selection mHighlight = NGUITools.AddSprite(mChild, atlas, highlightSprite); mHighlight.pivot = UIWidget.Pivot.TopLeft; mHighlight.color = highlightColor; UISpriteData hlsp = mHighlight.GetAtlasSprite(); if (hlsp == null) { return; } float hlspHeight = hlsp.borderTop; float fontHeight = activeFontSize; float dynScale = activeFontScale; float labelHeight = fontHeight * dynScale; float x = 0f, y = -padding.y; List <UILabel> labels = new List <UILabel>(); // Clear the selection if it's no longer present if (!items.Contains(mSelectedItem)) { mSelectedItem = null; } // Run through all items and create labels for each one for (int i = 0, imax = items.Count; i < imax; ++i) { string s = items[i]; UILabel lbl = NGUITools.AddWidget <UILabel>(mChild); lbl.name = i.ToString(); lbl.pivot = UIWidget.Pivot.TopLeft; lbl.bitmapFont = bitmapFont; lbl.trueTypeFont = trueTypeFont; lbl.fontSize = fontSize; lbl.fontStyle = fontStyle; lbl.text = isLocalized ? Localization.Get(s) : s; lbl.color = textColor; lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x - lbl.pivotOffset.x, y, -1f); lbl.overflowMethod = UILabel.Overflow.ResizeFreely; lbl.alignment = alignment; labels.Add(lbl); y -= labelHeight; y -= padding.y; x = Mathf.Max(x, lbl.printedSize.x); // Add an event listener UIEventListener listener = UIEventListener.Get(lbl.gameObject); listener.onHover = OnItemHover; listener.onPress = OnItemPress; listener.onClick = OnItemClick; listener.parameter = s; // Move the selection here if this is the right label if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem))) { Highlight(lbl, true); } // Add this label to the list mLabelList.Add(lbl); } // The triggering widget's width should be the minimum allowed width x = Mathf.Max(x, bounds.size.x * dynScale - (bgPadding.x + padding.x) * 2f); float cx = x; Vector3 bcCenter = new Vector3(cx * 0.5f, -labelHeight * 0.5f, 0f); Vector3 bcSize = new Vector3(cx, (labelHeight + padding.y), 1f); // Run through all labels and add colliders for (int i = 0, imax = labels.Count; i < imax; ++i) { UILabel lbl = labels[i]; NGUITools.AddWidgetCollider(lbl.gameObject); lbl.autoResizeBoxCollider = false; BoxCollider bc = lbl.GetComponent <BoxCollider>(); if (bc != null) { bcCenter.z = bc.center.z; bc.center = bcCenter; bc.size = bcSize; } else { BoxCollider2D b2d = lbl.GetComponent <BoxCollider2D>(); b2d.offset = bcCenter; b2d.size = bcSize; } } int lblWidth = Mathf.RoundToInt(x); x += (bgPadding.x + padding.x) * 2f; y -= bgPadding.y; // Scale the background sprite to envelop the entire set of items mBackground.width = Mathf.RoundToInt(x); mBackground.height = Mathf.RoundToInt(-y + bgPadding.y); // Set the label width to make alignment work for (int i = 0, imax = labels.Count; i < imax; ++i) { UILabel lbl = labels[i]; lbl.overflowMethod = UILabel.Overflow.ShrinkContent; lbl.width = lblWidth; } // Scale the highlight sprite to envelop a single item float scaleFactor = 2f * atlas.pixelSize; float w = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor; float h = labelHeight + hlspHeight * scaleFactor; mHighlight.width = Mathf.RoundToInt(w); mHighlight.height = Mathf.RoundToInt(h); bool placeAbove = (position == Position.Above); if (position == Position.Auto) { UICamera cam = UICamera.FindCameraForLayer((UICamera.selectedObject ?? gameObject).layer); if (cam != null) { Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(pos); placeAbove = (viewPos.y < 0.5f); } } // If the list should be animated, let's animate it by expanding it if (isAnimated) { float bottom = y + labelHeight; Animate(mHighlight, placeAbove, bottom); for (int i = 0, imax = labels.Count; i < imax; ++i) { Animate(labels[i], placeAbove, bottom); } AnimateColor(mBackground); AnimateScale(mBackground, placeAbove, bottom); } // If we need to place the popup list above the item, we need to reposition everything by the size of the list if (placeAbove) { t.localPosition = new Vector3(min.x, max.y - y - bgPadding.y, min.z); } min = t.localPosition; max.x = min.x + mBackground.width; max.y = min.y + mBackground.height; max.z = min.z; Vector3 offset = mPanel.CalculateConstrainOffset(min, max); t.localPosition += offset; } else { OnSelect(false); } }
/// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { // Only the first UI layer should be processing events if (!Application.isPlaying || !handlesEvents) return; current = this; // Update mouse input if (useMouse || (useTouch && mIsEditor)) ProcessMouse(); // Process touch input if (useTouch) ProcessTouches(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mSel != null && ((cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) || (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)))) selectedObject = null; // Forward the input to the selected object if (mSel != null) { string input = Input.inputString; // Adding support for some macs only having the "Delete" key instead of "Backspace" if (useKeyboard && Input.GetKeyDown(KeyCode.Delete)) input += "\b"; if (input.Length > 0) { if (!stickyTooltip && mTooltip != null) ShowTooltip(false); Notify(mSel, "OnInput", input); } } else inputHasFocus = false; // Update the keyboard and joystick events if (mSel != null) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = Input.GetAxis(scrollAxisName); if (scroll != 0f) Notify(mHover, "OnScroll", scroll); if (showTooltips && mTooltipTime != 0f && (mTooltipTime < Time.realtimeSinceStartup || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; }
/// <summary> /// React to any additional keys, such as Tab. /// </summary> public virtual void OnKey(KeyCode key) { if (UIPopupList.isOpen) { return; } if (mLastFrame == Time.frameCount) { return; } mLastFrame = Time.frameCount; if (key == KeyCode.Tab) { var go = onTab; if (go == null) { if (UICamera.GetKey(KeyCode.LeftShift) || UICamera.GetKey(KeyCode.RightShift)) { go = GetLeft(); if (go == null) { go = GetUp(); } if (go == null) { go = GetDown(); } if (go == null) { go = GetRight(); } } else { go = GetRight(); if (go == null) { go = GetDown(); } if (go == null) { go = GetUp(); } if (go == null) { go = GetLeft(); } } } if (go != null) { UICamera.currentScheme = UICamera.ControlScheme.Controller; UICamera.hoveredObject = go; UIInput inp = go.GetComponent <UIInput>(); if (inp != null) { inp.isSelected = true; } } } }
/// <summary> /// Process all events. /// </summary> void ProcessEvents () { current = this; NGUIDebug.debugRaycast = debug; // Process touch events first if (useTouch) ProcessTouches(); else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Update the keyboard and joystick events if ((useKeyboard || useController) && !disableController && !ignoreControllerInput) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = !string.IsNullOrEmpty(scrollAxisName) ? GetAxis(scrollAxisName) : 0f; if (scroll != 0f) { if (onScroll != null) onScroll(mHover, scroll); Notify(mHover, "OnScroll", scroll); } if (currentScheme == ControlScheme.Mouse && showTooltips && mTooltipTime != 0f && !UIPopupList.isOpen && mMouse[0].dragged == null && (mTooltipTime < RealTime.time || GetKey(KeyCode.LeftShift) || GetKey(KeyCode.RightShift))) { currentTouch = mMouse[0]; currentTouchID = -1; ShowTooltip(mHover); } } if (mTooltip != null && !NGUITools.GetActive(mTooltip)) ShowTooltip(null); current = null; currentTouchID = -100; }
private void OnPress(bool isPressed) { if (base.enabled) { if (!mStarted) { Start(); } TweenRotation.Begin(tweenTarget.gameObject, duration, isPressed ? (mRot * Quaternion.Euler(pressed)) : ((!UICamera.IsHighlighted(base.gameObject)) ? mRot : (mRot * Quaternion.Euler(hover)))).method = UITweener.Method.EaseInOut; } }