活动介绍

public void OnEnable() { for (int i = 0; i < panel.transform.childCount; i++) { Destroy(panel.transform.GetChild(i).gameObject); } for (int i = 0; i < showPanel.transform.childCount; i++) { Destroy(showPanel.transform.GetChild(i).gameObject); } for (int i = 0; i < 18; i++) { GameObject beforeArror = Instantiate(beforeArrorPrefab); beforeArror.transform.SetParent(panel.transform, false); beforeArror.name = "Arror" + i.ToString(); } for (flag = 0; flag < ArrorManage.jiaNumber; flag++) { Transform jiaParent = panel.transform.Find("Arror" + flag.ToString()); GameObject jiaImage = Instantiate(jiaPrefab); jiaImage.transform.SetParent(jiaParent, false); jiaImage.transform.localPosition = Vector2.zero; jiaImage.name = "jia"; } for (int i = 0; i < ArrorManage.dunNumber; i++) { Transform dunParent = panel.transform.Find("Arror" + flag.ToString()); GameObject dunImage = Instantiate(dunPrefab); dunImage.transform.SetParent(dunParent, false); dunImage.transform.localPosition = Vector2.zero; dunImage.name = "dun"; flag++; } }为什么第二次激活后第四五个循环没作用

时间: 2024-02-14 13:35:57 浏览: 172
根据代码,第四个循环是向panel中添加18个箭头,第五个循环是向panel中添加jiaNumber个加号,第六个循环是向panel中添加dunNumber个盾牌。如果第二次激活后第四五个循环没有作用,那么可能是因为panel中已经存在了这些对象,导致添加不上去。你可以在循环前先检查一下panel中是否已经存在这些对象,如果存在就跳过添加的操作。另外,如果你想要在第二次激活后重新添加这些对象,可以在OnDisable()方法中将panel和showPanel中的所有子对象销毁,这样在下一次激活时就能重新添加了。
相关问题

public void OnEnable() { for (int i = 0; i < panel.transform.childCount; i++) { Destroy(panel.transform.GetChild(i).gameObject); } for (int i = 0; i < showPanel.transform.childCount; i++) { Destroy(showPanel.transform.GetChild(i).gameObject); } for (int i = 0; i < 18; i++) { GameObject beforeArror = Instantiate(beforeArrorPrefab); beforeArror.transform.SetParent(panel.transform, false); beforeArror.name = "Arror" + i.ToString(); } for (int i = 0; i < ArrorManage.jiaNumber; i++) { Debug.Log(ArrorManage.jiaNumber); Transform jiaParent = panel.transform.Find("Arror" + i.ToString()); GameObject jiaImage = Instantiate(jiaPrefab); jiaImage.transform.SetParent(jiaParent, false); jiaImage.transform.localPosition = Vector2.zero; jiaImage.name = "jia"; flag++; } for (int i = 0; i < ArrorManage.dunNumber; i++) { Transform dunParent = panel.transform.Find("Arror" + flag.ToString()); GameObject dunImage = Instantiate(dunPrefab); dunImage.transform.SetParent(dunParent, false); dunImage.transform.localPosition = Vector2.zero; dunImage.name = "dun"; flag++; } }为什么第二次激活后第四五个循环没作用

这段代码中有一个变量`flag`,在第一个循环之前没有初始化,因此第二次激活时`flag`的值可能是不正确的,导致后面的循环没有执行。建议将`flag`的初始值在函数开始时设为0,例如在函数开头处添加`flag = 0;`。 此外,如果第二次激活后仍然没有执行第四五个循环,可以在代码中添加一些`Debug.Log`语句来输出变量的值,以便进行排查错误原因。

for (int i = 0; i < cityTransforms.childCount; i++) { gongJiChengShiBeans[i].city = cityTransforms.GetChild(i).gameObject.name; gongJiChengShiBeans[i].count = 1; gongJiChengShiBeans[i].type = (i == 0) ? 1 : (gongJiChengShiBeans[i - 1].type % 5) + 1; } 优化代码

为了优化这段代码,我注意到可以减少对 `cityTransforms.GetChild(i).gameObject` 的多次访问。此外,可以将 `(i == 0) ? 1 : (gongJiChengShiBeans[i - 1].type % 5) + 1` 的计算提取到循环外,避免重复计算。下面是优化后的代码: ```csharp int previousType = 1; for (int i = 0; i < cityTransforms.childCount; i++) { Transform childTransform = cityTransforms.GetChild(i); GongJiChengShiBean gongJiChengShiBean = gongJiChengShiBeans[i]; gongJiChengShiBean.city = childTransform.gameObject.name; gongJiChengShiBean.count = 1; gongJiChengShiBean.type = (previousType % 5) + 1; previousType = gongJiChengShiBean.type; } ``` 这样,代码中的 `cityTransforms.GetChild(i).gameObject` 只被访问一次,并且计算 `(previousType % 5) + 1` 只在循环外进行一次。这样可以提高代码的效率。
阅读全文

相关推荐

//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2015 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using System; using System.Collections.Generic; using System.IO; using System.Reflection; /// /// Helper class containing generic functions used throughout the UI library. /// static public class NGUITools { static AudioListener mListener; static bool mLoaded = false; static float mGlobalVolume = 1f; /// /// Globally accessible volume affecting all sounds played via NGUITools.PlaySound(). /// static public float soundVolume { get { if (!mLoaded) { mLoaded = true; mGlobalVolume = PlayerPrefs.GetFloat("Sound", 1f); } return mGlobalVolume; } set { if (mGlobalVolume != value) { mLoaded = true; mGlobalVolume = value; PlayerPrefs.SetFloat("Sound", value); } } } /// /// Helper function -- whether the disk access is allowed. /// static public bool fileAccess { get { return Application.platform != RuntimePlatform.WindowsWebPlayer && Application.platform != RuntimePlatform.OSXWebPlayer; } } /// /// Play the specified audio clip. /// static public AudioSource PlaySound (AudioClip clip) { return PlaySound(clip, 1f, 1f); } /// /// Play the specified audio clip with the specified volume. /// static public AudioSource PlaySound (AudioClip clip, float volume) { return PlaySound(clip, volume, 1f); } static float mLastTimestamp = 0f; static AudioClip mLastClip; /// /// Play the specified audio clip with the specified volume and pitch. /// static public AudioSource PlaySound (AudioClip clip, float volume, float pitch) { float time = Time.time; if (mLastClip == clip && mLastTimestamp + 0.1f > time) return null; mLastClip = clip; mLastTimestamp = time; volume *= soundVolume; if (clip != null && volume > 0.01f) { if (mListener == null || !NGUITools.GetActive(mListener)) { AudioListener[] listeners = GameObject.FindObjectsOfType(typeof(AudioListener)) as AudioListener[]; if (listeners != null) { for (int i = 0; i < listeners.Length; ++i) { if (NGUITools.GetActive(listeners[i])) { mListener = listeners[i]; break; } } } if (mListener == null) { Camera cam = Camera.main; if (cam == null) cam = GameObject.FindObjectOfType(typeof(Camera)) as Camera; if (cam != null) mListener = cam.gameObject.AddComponent<AudioListener>(); } } if (mListener != null && mListener.enabled && NGUITools.GetActive(mListener.gameObject)) { #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 AudioSource source = mListener.audio; #else AudioSource source = mListener.GetComponent<AudioSource>(); #endif if (source == null) source = mListener.gameObject.AddComponent<AudioSource>(); #if !UNITY_FLASH source.priority = 50; source.pitch = pitch; #endif source.PlayOneShot(clip, volume); return source; } } return null; } /// /// New WWW call can fail if the crossdomain policy doesn't check out. Exceptions suck. It's much more elegant to check for null instead. /// // static public WWW OpenURL (string url) // { //#if UNITY_FLASH // Debug.LogError("WWW is not yet implemented in Flash"); // return null; //#else // WWW www = null; // try { www = new WWW(url); } // catch (System.Exception ex) { Debug.LogError(ex.Message); } // return www; //#endif // } // /// // /// New WWW call can fail if the crossdomain policy doesn't check out. Exceptions suck. It's much more elegant to check for null instead. // /// // static public WWW OpenURL (string url, WWWForm form) // { // if (form == null) return OpenURL(url); //#if UNITY_FLASH // Debug.LogError("WWW is not yet implemented in Flash"); // return null; //#else // WWW www = null; // try { www = new WWW(url, form); } // catch (System.Exception ex) { Debug.LogError(ex != null ? ex.Message : "<null>"); } // return www; //#endif // } /// /// Same as Random.Range, but the returned value is between min and max, inclusive. /// Unity's Random.Range is less than max instead, unless min == max. /// This means Range(0,1) produces 0 instead of 0 or 1. That's unacceptable. /// static public int RandomRange (int min, int max) { if (min == max) return min; return UnityEngine.Random.Range(min, max + 1); } /// /// Returns the hierarchy of the object in a human-readable format. /// static public string GetHierarchy (GameObject obj) { if (obj == null) return ""; string path = obj.name; while (obj.transform.parent != null) { obj = obj.transform.parent.gameObject; path = obj.name + "\\" + path; } return path; } /// /// Find all active objects of specified type. /// static public T[] FindActive<T> () where T : Component { return GameObject.FindObjectsOfType(typeof(T)) as T[]; } /// /// Find the camera responsible for drawing the objects on the specified layer. /// static public Camera FindCameraForLayer (int layer) { int layerMask = 1 << layer; Camera cam; for (int i = 0; i < UICamera.list.size; ++i) { cam = UICamera.list.buffer[i].cachedCamera; if (cam && (cam.cullingMask & layerMask) != 0) return cam; } cam = Camera.main; if (cam && (cam.cullingMask & layerMask) != 0) return cam; #if UNITY_4_3 || UNITY_FLASH Camera[] cameras = NGUITools.FindActive<Camera>(); for (int i = 0, imax = cameras.Length; i < imax; ++i) #else Camera[] cameras = new Camera[Camera.allCamerasCount]; int camerasFound = Camera.GetAllCameras(cameras); for (int i = 0; i < camerasFound; ++i) #endif { cam = cameras[i]; if (cam && cam.enabled && (cam.cullingMask & layerMask) != 0) return cam; } return null; } /// /// Add a collider to the game object containing one or more widgets. /// static public void AddWidgetCollider (GameObject go) { AddWidgetCollider(go, false); } /// /// Add a collider to the game object containing one or more widgets. /// static public void AddWidgetCollider (GameObject go, bool considerInactive) { if (go != null) { // 3D collider Collider col = go.GetComponent<Collider>(); BoxCollider box = col as BoxCollider; if (box != null) { UpdateWidgetCollider(box, considerInactive); return; } // Is there already another collider present? If so, do nothing. if (col != null) return; // 2D collider BoxCollider2D box2 = go.GetComponent<BoxCollider2D>(); if (box2 != null) { UpdateWidgetCollider(box2, considerInactive); return; } UICamera ui = UICamera.FindCameraForLayer(go.layer); if (ui != null && (ui.eventType == UICamera.EventType.World_2D || ui.eventType == UICamera.EventType.UI_2D)) { box2 = go.AddComponent<BoxCollider2D>(); box2.isTrigger = true; #if UNITY_EDITOR UnityEditor.Undo.RegisterCreatedObjectUndo(box2, "Add Collider"); #endif UIWidget widget = go.GetComponent<UIWidget>(); if (widget != null) widget.autoResizeBoxCollider = true; UpdateWidgetCollider(box2, considerInactive); return; } else { box = go.AddComponent<BoxCollider>(); #if UNITY_EDITOR UnityEditor.Undo.RegisterCreatedObjectUndo(box, "Add Collider"); #endif box.isTrigger = true; UIWidget widget = go.GetComponent<UIWidget>(); if (widget != null) widget.autoResizeBoxCollider = true; UpdateWidgetCollider(box, considerInactive); } } return; } /// /// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions. /// static public void UpdateWidgetCollider (GameObject go) { UpdateWidgetCollider(go, false); } /// /// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions. /// static public void UpdateWidgetCollider (GameObject go, bool considerInactive) { if (go != null) { BoxCollider bc = go.GetComponent<BoxCollider>(); if (bc != null) { UpdateWidgetCollider(bc, considerInactive); return; } BoxCollider2D box2 = go.GetComponent<BoxCollider2D>(); if (box2 != null) UpdateWidgetCollider(box2, considerInactive); } } /// /// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions. /// static public void UpdateWidgetCollider (BoxCollider box, bool considerInactive) { if (box != null) { GameObject go = box.gameObject; UIWidget w = go.GetComponent<UIWidget>(); if (w != null) { Vector4 dr = w.drawRegion; if (dr.x != 0f || dr.y != 0f || dr.z != 1f || dr.w != 1f) { Vector4 region = w.drawingDimensions; box.center = new Vector3((region.x + region.z) * 0.5f, (region.y + region.w) * 0.5f); box.size = new Vector3(region.z - region.x, region.w - region.y); } else { Vector3[] corners = w.localCorners; box.center = Vector3.Lerp(corners[0], corners[2], 0.5f); box.size = corners[2] - corners[0]; } } else { Bounds b = NGUIMath.CalculateRelativeWidgetBounds(go.transform, considerInactive); box.center = b.center; box.size = new Vector3(b.size.x, b.size.y, 0f); } #if UNITY_EDITOR NGUITools.SetDirty(box); #endif } } /// /// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions. /// static public void UpdateWidgetCollider (BoxCollider2D box, bool considerInactive) { if (box != null) { GameObject go = box.gameObject; UIWidget w = go.GetComponent<UIWidget>(); if (w != null) { Vector3[] corners = w.localCorners; #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 box.center = Vector3.Lerp(corners[0], corners[2], 0.5f); #else box.offset = Vector3.Lerp(corners[0], corners[2], 0.5f); #endif box.size = corners[2] - corners[0]; } else { Bounds b = NGUIMath.CalculateRelativeWidgetBounds(go.transform, considerInactive); #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 box.center = b.center; #else box.offset = b.center; #endif box.size = new Vector2(b.size.x, b.size.y); } #if UNITY_EDITOR NGUITools.SetDirty(box); #endif } } /// /// Helper function that returns the string name of the type. /// static public string GetTypeName<T> () { string s = typeof(T).ToString(); if (s.StartsWith("UI")) s = s.Substring(2); else if (s.StartsWith("UnityEngine.")) s = s.Substring(12); return s; } /// /// Helper function that returns the string name of the type. /// static public string GetTypeName (UnityEngine.Object obj) { if (obj == null) return "Null"; string s = obj.GetType().ToString(); if (s.StartsWith("UI")) s = s.Substring(2); else if (s.StartsWith("UnityEngine.")) s = s.Substring(12); return s; } /// /// Convenience method that works without warnings in both Unity 3 and 4. /// static public void RegisterUndo (UnityEngine.Object obj, string name) { #if UNITY_EDITOR UnityEditor.Undo.RecordObject(obj, name); NGUITools.SetDirty(obj); #endif } /// /// Convenience function that marks the specified object as dirty in the Unity Editor. /// static public void SetDirty (UnityEngine.Object obj) { #if UNITY_EDITOR if (obj) { //if (obj is Component) Debug.Log(NGUITools.GetHierarchy((obj as Component).gameObject), obj); //else if (obj is GameObject) Debug.Log(NGUITools.GetHierarchy(obj as GameObject), obj); //else Debug.Log("Hmm... " + obj.GetType(), obj); UnityEditor.EditorUtility.SetDirty(obj); } #endif } /// /// Add a new child game object. /// static public GameObject AddChild (GameObject parent) { return AddChild(parent, true); } /// /// Add a new child game object. /// static public GameObject AddChild (GameObject parent, bool undo) { GameObject go = new GameObject(); #if UNITY_EDITOR if (undo) UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Create Object"); #endif if (parent != null) { Transform t = go.transform; t.parent = parent.transform; t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; go.layer = parent.layer; } return go; } /// /// Instantiate an object and add it to the specified parent. /// static public GameObject AddChild (GameObject parent, GameObject prefab) { GameObject go = GameObject.Instantiate(prefab) as GameObject; #if UNITY_EDITOR UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Create Object"); #endif if (go != null && parent != null) { Transform t = go.transform; t.parent = parent.transform; t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; go.layer = parent.layer; } return go; } /// /// Calculate the game object's depth based on the widgets within, and also taking panel depth into consideration. /// static public int CalculateRaycastDepth (GameObject go) { UIWidget w = go.GetComponent<UIWidget>(); if (w != null) return w.raycastDepth; UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>(); if (widgets.Length == 0) return 0; int depth = int.MaxValue; for (int i = 0, imax = widgets.Length; i < imax; ++i) { if (widgets[i].enabled) depth = Mathf.Min(depth, widgets[i].raycastDepth); } return depth; } /// /// Gathers all widgets and calculates the depth for the next widget. /// static public int CalculateNextDepth (GameObject go) { int depth = -1; UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>(); for (int i = 0, imax = widgets.Length; i < imax; ++i) depth = Mathf.Max(depth, widgets[i].depth); return depth + 1; } /// /// Gathers all widgets and calculates the depth for the next widget. /// static public int CalculateNextDepth (GameObject go, bool ignoreChildrenWithColliders) { if (ignoreChildrenWithColliders) { int depth = -1; UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>(); for (int i = 0, imax = widgets.Length; i < imax; ++i) { UIWidget w = widgets[i]; #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 if (w.cachedGameObject != go && (w.collider != null || w.GetComponent<Collider2D>() != null)) continue; #else if (w.cachedGameObject != go && (w.GetComponent<Collider>() != null || w.GetComponent<Collider2D>() != null)) continue; #endif depth = Mathf.Max(depth, w.depth); } return depth + 1; } return CalculateNextDepth(go); } /// /// Adjust the widgets' depth by the specified value. /// Returns '0' if nothing was adjusted, '1' if panels were adjusted, and '2' if widgets were adjusted. /// static public int AdjustDepth (GameObject go, int adjustment) { if (go != null) { UIPanel panel = go.GetComponent<UIPanel>(); if (panel != null) { UIPanel[] panels = go.GetComponentsInChildren<UIPanel>(true); for (int i = 0; i < panels.Length; ++i) { UIPanel p = panels[i]; #if UNITY_EDITOR RegisterUndo(p, "Depth Change"); #endif p.depth = p.depth + adjustment; } return 1; } else { panel = FindInParents<UIPanel>(go); if (panel == null) return 0; UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>(true); for (int i = 0, imax = widgets.Length; i < imax; ++i) { UIWidget w = widgets[i]; if (w.panel != panel) continue; #if UNITY_EDITOR RegisterUndo(w, "Depth Change"); #endif w.depth = w.depth + adjustment; } return 2; } } return 0; } /// /// Bring all of the widgets on the specified object forward. /// static public void BringForward (GameObject go) { int val = AdjustDepth(go, 1000); if (val == 1) NormalizePanelDepths(); else if (val == 2) NormalizeWidgetDepths(); } /// /// Push all of the widgets on the specified object back, making them appear behind everything else. /// static public void PushBack (GameObject go) { int val = AdjustDepth(go, -1000); if (val == 1) NormalizePanelDepths(); else if (val == 2) NormalizeWidgetDepths(); } /// /// Normalize the depths of all the widgets and panels in the scene, making them start from 0 and remain in order. /// static public void NormalizeDepths () { NormalizeWidgetDepths(); NormalizePanelDepths(); } /// /// Normalize the depths of all the widgets in the scene, making them start from 0 and remain in order. /// static public void NormalizeWidgetDepths () { NormalizeWidgetDepths(FindActive<UIWidget>()); } /// /// Normalize the depths of all the widgets in the scene, making them start from 0 and remain in order. /// static public void NormalizeWidgetDepths (GameObject go) { NormalizeWidgetDepths(go.GetComponentsInChildren<UIWidget>()); } /// /// Normalize the depths of all the widgets in the scene, making them start from 0 and remain in order. /// static public void NormalizeWidgetDepths (UIWidget[] list) { int size = list.Length; if (size > 0) { Array.Sort(list, UIWidget.FullCompareFunc); int start = 0; int current = list[0].depth; for (int i = 0; i < size; ++i) { UIWidget w = list[i]; if (w.depth == current) { w.depth = start; } else { current = w.depth; w.depth = ++start; } } } } /// /// Normalize the depths of all the panels in the scene, making them start from 0 and remain in order. /// static public void NormalizePanelDepths () { UIPanel[] list = FindActive<UIPanel>(); int size = list.Length; if (size > 0) { Array.Sort(list, UIPanel.CompareFunc); int start = 0; int current = list[0].depth; for (int i = 0; i < size; ++i) { UIPanel p = list[i]; if (p.depth == current) { p.depth = start; } else { current = p.depth; p.depth = ++start; } } } } /// /// Create a new UI. /// static public UIPanel CreateUI (bool advanced3D) { return CreateUI(null, advanced3D, -1); } /// /// Create a new UI. /// static public UIPanel CreateUI (bool advanced3D, int layer) { return CreateUI(null, advanced3D, layer); } /// /// Create a new UI. /// static public UIPanel CreateUI (Transform trans, bool advanced3D, int layer) { // Find the existing UI Root UIRoot root = (trans != null) ? NGUITools.FindInParents<UIRoot>(trans.gameObject) : null; if (root == null && UIRoot.list.Count > 0) { foreach (UIRoot r in UIRoot.list) { if (r.gameObject.layer == layer) { root = r; break; } } } // Try to find an existing panel if (root == null) { for (int i = 0, imax = UIPanel.list.Count; i < imax; ++i) { UIPanel p = UIPanel.list[i]; GameObject go = p.gameObject; if (go.hideFlags == HideFlags.None && go.layer == layer) { trans.parent = p.transform; trans.localScale = Vector3.one; return p; } } } // If we are working with a different UI type, we need to treat it as a brand-new one instead if (root != null) { UICamera cam = root.GetComponentInChildren<UICamera>(); #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 if (cam != null && cam.camera.isOrthoGraphic == advanced3D) #else if (cam != null && cam.GetComponent<Camera>().orthographic == advanced3D) #endif { trans = null; root = null; } } // If no root found, create one if (root == null) { GameObject go = NGUITools.AddChild(null, false); root = go.AddComponent<UIRoot>(); // Automatically find the layers if none were specified if (layer == -1) layer = LayerMask.NameToLayer("UI"); if (layer == -1) layer = LayerMask.NameToLayer("2D UI"); go.layer = layer; if (advanced3D) { go.name = "UI Root (3D)"; root.scalingStyle = UIRoot.Scaling.Constrained; } else { go.name = "UI Root"; root.scalingStyle = UIRoot.Scaling.Flexible; } } // Find the first panel UIPanel panel = root.GetComponentInChildren<UIPanel>(); if (panel == null) { // Find other active cameras in the scene Camera[] cameras = NGUITools.FindActive<Camera>(); float depth = -1f; bool colorCleared = false; int mask = (1 << root.gameObject.layer); for (int i = 0; i < cameras.Length; ++i) { Camera c = cameras[i]; // If the color is being cleared, we won't need to if (c.clearFlags == CameraClearFlags.Color || c.clearFlags == CameraClearFlags.Skybox) colorCleared = true; // Choose the maximum depth depth = Mathf.Max(depth, c.depth); // Make sure this camera can't see the UI c.cullingMask = (c.cullingMask & (~mask)); } // Create a camera that will draw the UI Camera cam = NGUITools.AddChild<Camera>(root.gameObject, false); cam.gameObject.AddComponent<UICamera>(); cam.clearFlags = colorCleared ? CameraClearFlags.Depth : CameraClearFlags.Color; cam.backgroundColor = Color.grey; cam.cullingMask = mask; cam.depth = depth + 1f; if (advanced3D) { cam.nearClipPlane = 0.1f; cam.farClipPlane = 4f; cam.transform.localPosition = new Vector3(0f, 0f, -700f); } else { cam.orthographic = true; cam.orthographicSize = 1; cam.nearClipPlane = -10; cam.farClipPlane = 10; } // Make sure there is an audio listener present AudioListener[] listeners = NGUITools.FindActive<AudioListener>(); if (listeners == null || listeners.Length == 0) cam.gameObject.AddComponent<AudioListener>(); // Add a panel to the root panel = root.gameObject.AddComponent<UIPanel>(); #if UNITY_EDITOR UnityEditor.Selection.activeGameObject = panel.gameObject; #endif } if (trans != null) { // Find the root object while (trans.parent != null) trans = trans.parent; if (NGUITools.IsChild(trans, panel.transform)) { // Odd hierarchy -- can't reparent panel = trans.gameObject.AddComponent<UIPanel>(); } else { // Reparent this root object to be a child of the panel trans.parent = panel.transform; trans.localScale = Vector3.one; trans.localPosition = Vector3.zero; SetChildLayer(panel.cachedTransform, panel.cachedGameObject.layer); } } return panel; } /// /// Helper function that recursively sets all children with widgets' game objects layers to the specified value. /// static public void SetChildLayer (Transform t, int layer) { for (int i = 0; i < t.childCount; ++i) { Transform child = t.GetChild(i); child.gameObject.layer = layer; SetChildLayer(child, layer); } } /// /// Add a child object to the specified parent and attaches the specified script to it. /// static public T AddChild<T> (GameObject parent) where T : Component { GameObject go = AddChild(parent); go.name = GetTypeName<T>(); return go.AddComponent<T>(); } /// /// Add a child object to the specified parent and attaches the specified script to it. /// static public T AddChild<T> (GameObject parent, bool undo) where T : Component { GameObject go = AddChild(parent, undo); go.name = GetTypeName<T>(); return go.AddComponent<T>(); } /// /// Add a new widget of specified type. /// static public T AddWidget<T> (GameObject go) where T : UIWidget { int depth = CalculateNextDepth(go); // Create the widget and place it above other widgets T widget = AddChild<T>(go); widget.width = 100; widget.height = 100; widget.depth = depth; return widget; } /// /// Add a new widget of specified type. /// static public T AddWidget<T> (GameObject go, int depth) where T : UIWidget { // Create the widget and place it above other widgets T widget = AddChild<T>(go); widget.width = 100; widget.height = 100; widget.depth = depth; return widget; } /// /// Add a sprite appropriate for the specified atlas sprite. /// It will be sliced if the sprite has an inner rect, and a regular sprite otherwise. /// static public UISprite AddSprite (GameObject go, UIAtlas atlas, string spriteName) { UISpriteData sp = (atlas != null) ? atlas.GetSprite(spriteName) : null; UISprite sprite = AddWidget<UISprite>(go); sprite.type = (sp == null || !sp.hasBorder) ? UISprite.Type.Simple : UISprite.Type.Sliced; sprite.atlas = atlas; sprite.spriteName = spriteName; return sprite; } /// /// Get the rootmost object of the specified game object. /// static public GameObject GetRoot (GameObject go) { Transform t = go.transform; for (; ; ) { Transform parent = t.parent; if (parent == null) break; t = parent; } return t.gameObject; } /// /// Finds the specified component on the game object or one of its parents. /// static public T FindInParents<T> (GameObject go) where T : Component { if (go == null) return null; // Commented out because apparently it causes Unity 4.5.3 to lag horribly: // http://www.tasharen.com/forum/index.php?topic=10882.0 //#if UNITY_4_3 #if UNITY_FLASH object comp = go.GetComponent<T>(); #else T comp = go.GetComponent<T>(); #endif if (comp == null) { Transform t = go.transform.parent; while (t != null && comp == null) { comp = t.gameObject.GetComponent<T>(); t = t.parent; } } #if UNITY_FLASH return (T)comp; #else return comp; #endif //#else // return go.GetComponentInParent<T>(); //#endif } /// /// Finds the specified component on the game object or one of its parents. /// static public T FindInParents<T> (Transform trans) where T : Component { if (trans == null) return null; #if UNITY_4_3 #if UNITY_FLASH object comp = trans.GetComponent<T>(); #else T comp = trans.GetComponent<T>(); #endif if (comp == null) { Transform t = trans.transform.parent; while (t != null && comp == null) { comp = t.gameObject.GetComponent<T>(); t = t.parent; } } #if UNITY_FLASH return (T)comp; #else return comp; #endif #else return trans.GetComponentInParent<T>(); #endif } /// /// Destroy the specified object, immediately if in edit mode. /// static public void Destroy (UnityEngine.Object obj) { if (obj != null) { if (obj is Transform) obj = (obj as Transform).gameObject; if (Application.isPlaying) { if (obj is GameObject) { GameObject go = obj as GameObject; go.transform.parent = null; } UnityEngine.Object.Destroy(obj); } else UnityEngine.Object.DestroyImmediate(obj); } } /// /// Destroy the specified object immediately, unless not in the editor, in which case the regular Destroy is used instead. /// static public void DestroyImmediate (UnityEngine.Object obj) { if (obj != null) { if (Application.isEditor) UnityEngine.Object.DestroyImmediate(obj); else UnityEngine.Object.Destroy(obj); } } /// /// Call the specified function on all objects in the scene. /// static public void Broadcast (string funcName) { GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[]; for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, SendMessageOptions.DontRequireReceiver); } /// /// Call the specified function on all objects in the scene. /// static public void Broadcast (string funcName, object param) { GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[]; for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, param, SendMessageOptions.DontRequireReceiver); } /// /// Determines whether the 'parent' contains a 'child' in its hierarchy. /// static public bool IsChild (Transform parent, Transform child) { if (parent == null || child == null) return false; while (child != null) { if (child == parent) return true; child = child.parent; } return false; } /// /// Activate the specified object and all of its children. /// static void Activate (Transform t) { Activate(t, false); } /// /// Activate the specified object and all of its children. /// static void Activate (Transform t, bool compatibilityMode) { SetActiveSelf(t.gameObject, true); if (compatibilityMode) { // If there is even a single enabled child, then we're using a Unity 4.0-based nested active state scheme. for (int i = 0, imax = t.childCount; i < imax; ++i) { Transform child = t.GetChild(i); if (child.gameObject.activeSelf) return; } // If this point is reached, then all the children are disabled, so we must be using a Unity 3.5-based active state scheme. for (int i = 0, imax = t.childCount; i < imax; ++i) { Transform child = t.GetChild(i); Activate(child, true); } } } /// /// Deactivate the specified object and all of its children. /// static void Deactivate (Transform t) { SetActiveSelf(t.gameObject, false); } /// /// SetActiveRecursively enables children before parents. This is a problem when a widget gets re-enabled /// and it tries to find a panel on its parent. /// static public void SetActive (GameObject go, bool state) { SetActive(go, state, true); } /// /// SetActiveRecursively enables children before parents. This is a problem when a widget gets re-enabled /// and it tries to find a panel on its parent. /// static public void SetActive (GameObject go, bool state, bool compatibilityMode) { if (go) { if (state) { Activate(go.transform, compatibilityMode); #if UNITY_EDITOR if (Application.isPlaying) #endif CallCreatePanel(go.transform); } else Deactivate(go.transform); } } /// /// Ensure that all widgets have had their panels created, forcing the update right away rather than on the following frame. /// [System.Diagnostics.DebuggerHidden] [System.Diagnostics.DebuggerStepThrough] static void CallCreatePanel (Transform t) { UIWidget w = t.GetComponent<UIWidget>(); if (w != null) w.CreatePanel(); for (int i = 0, imax = t.childCount; i < imax; ++i) CallCreatePanel(t.GetChild(i)); } /// /// Activate or deactivate children of the specified game object without changing the active state of the object itself. /// static public void SetActiveChildren (GameObject go, bool state) { Transform t = go.transform; if (state) { for (int i = 0, imax = t.childCount; i < imax; ++i) { Transform child = t.GetChild(i); Activate(child); } } else { for (int i = 0, imax = t.childCount; i < imax; ++i) { Transform child = t.GetChild(i); Deactivate(child); } } } /// /// Helper function that returns whether the specified MonoBehaviour is active. /// [System.Obsolete("Use NGUITools.GetActive instead")] static public bool IsActive (Behaviour mb) { return mb != null && mb.enabled && mb.gameObject.activeInHierarchy; } /// /// Helper function that returns whether the specified MonoBehaviour is active. /// [System.Diagnostics.DebuggerHidden] [System.Diagnostics.DebuggerStepThrough] static public bool GetActive (Behaviour mb) { return mb && mb.enabled && mb.gameObject.activeInHierarchy; } /// /// Unity4 has changed GameObject.active to GameObject.activeself. /// [System.Diagnostics.DebuggerHidden] [System.Diagnostics.DebuggerStepThrough] static public bool GetActive (GameObject go) { return go && go.activeInHierarchy; } /// /// Unity4 has changed GameObject.active to GameObject.SetActive. /// [System.Diagnostics.DebuggerHidden] [System.Diagnostics.DebuggerStepThrough] static public void SetActiveSelf (GameObject go, bool state) { go.SetActive(state); } /// /// Recursively set the game object's layer. /// static public void SetLayer (GameObject go, int layer) { go.layer = layer; Transform t = go.transform; for (int i = 0, imax = t.childCount; i < imax; ++i) { Transform child = t.GetChild(i); SetLayer(child.gameObject, layer); } } /// /// Helper function used to make the vector use integer numbers. /// static public Vector3 Round (Vector3 v) { v.x = Mathf.Round(v.x); v.y = Mathf.Round(v.y); v.z = Mathf.Round(v.z); return v; } /// /// Make the specified selection pixel-perfect. /// static public void MakePixelPerfect (Transform t) { UIWidget w = t.GetComponent<UIWidget>(); if (w != null) w.MakePixelPerfect(); if (t.GetComponent<UIAnchor>() == null && t.GetComponent<UIRoot>() == null) { #if UNITY_EDITOR RegisterUndo(t, "Make Pixel-Perfect"); #endif t.localPosition = Round(t.localPosition); t.localScale = Round(t.localScale); } // Recurse into children for (int i = 0, imax = t.childCount; i < imax; ++i) MakePixelPerfect(t.GetChild(i)); } /// /// Save the specified binary data into the specified file. /// static public bool Save (string fileName, byte[] bytes) { #if UNITY_WEBPLAYER || UNITY_FLASH || UNITY_METRO || UNITY_WP8 || UNITY_WP_8_1 return false; #else if (!NGUITools.fileAccess) return false; string path = ""; if (bytes == null) { if (File.Exists(path)) File.Delete(path); return true; } FileStream file = null; try { file = File.Create(path); } catch (System.Exception ex) { Debug.LogError(ex.Message); return false; } file.Write(bytes, 0, bytes.Length); file.Close(); return true; #endif } /// /// Load all binary data from the specified file. /// static public byte[] Load (string fileName) { #if UNITY_WEBPLAYER || UNITY_FLASH || UNITY_METRO || UNITY_WP8 || UNITY_WP_8_1 return null; #else if (!NGUITools.fileAccess) return null; string path = ""; if (File.Exists(path)) { return File.ReadAllBytes(path); } return null; #endif } /// /// Pre-multiply shaders result in a black outline if this operation is done in the shader. It's better to do it outside. /// static public Color ApplyPMA (Color c) { if (c.a != 1f) { c.r *= c.a; c.g *= c.a; c.b *= c.a; } return c; } /// /// Inform all widgets underneath the specified object that the parent has changed. /// static public void MarkParentAsChanged (GameObject go) { UIRect[] rects = go.GetComponentsInChildren<UIRect>(); for (int i = 0, imax = rects.Length; i < imax; ++i) rects[i].ParentHasChanged(); } /// /// Access to the clipboard via undocumented APIs. /// static public string clipboard { get { TextEditor te = new TextEditor(); te.Paste(); return te.content.text; } set { TextEditor te = new TextEditor(); te.content = new GUIContent(value); te.OnFocus(); te.Copy(); } } [System.Obsolete("Use NGUIText.EncodeColor instead")] static public string EncodeColor (Color c) { return NGUIText.EncodeColor24(c); } [System.Obsolete("Use NGUIText.ParseColor instead")] static public Color ParseColor (string text, int offset) { return NGUIText.ParseColor24(text, offset); } [System.Obsolete("Use NGUIText.StripSymbols instead")] static public string StripSymbols (string text) { return NGUIText.StripSymbols(text); } /// /// Extension for the game object that checks to see if the component already exists before adding a new one. /// If the component is already present it will be returned instead. /// static public T AddMissingComponent<T> (this GameObject go) where T : Component { #if UNITY_FLASH object comp = go.GetComponent<T>(); #else T comp = go.GetComponent<T>(); #endif if (comp == null) { #if UNITY_EDITOR if (!Application.isPlaying) RegisterUndo(go, "Add " + typeof(T)); #endif comp = go.AddComponent<T>(); } #if UNITY_FLASH return (T)comp; #else return comp; #endif } // Temporary variable to avoid GC allocation static Vector3[] mSides = new Vector3[4]; /// /// Get sides relative to the specified camera. The order is left, top, right, bottom. /// static public Vector3[] GetSides (this Camera cam) { return cam.GetSides(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), null); } /// /// Get sides relative to the specified camera. The order is left, top, right, bottom. /// static public Vector3[] GetSides (this Camera cam, float depth) { return cam.GetSides(depth, null); } /// /// Get sides relative to the specified camera. The order is left, top, right, bottom. /// static public Vector3[] GetSides (this Camera cam, Transform relativeTo) { return cam.GetSides(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), relativeTo); } /// /// Get sides relative to the specified camera. The order is left, top, right, bottom. /// static public Vector3[] GetSides (this Camera cam, float depth, Transform relativeTo) { #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 if (cam.isOrthoGraphic) #else if (cam.orthographic) #endif { float os = cam.orthographicSize; float x0 = -os; float x1 = os; float y0 = -os; float y1 = os; Rect rect = cam.rect; Vector2 size = screenSize; float aspect = size.x / size.y; aspect *= rect.width / rect.height; x0 *= aspect; x1 *= aspect; // We want to ignore the scale, as scale doesn't affect the camera's view region in Unity Transform t = cam.transform; Quaternion rot = t.rotation; Vector3 pos = t.position; int w = Mathf.RoundToInt(size.x); int h = Mathf.RoundToInt(size.y); if ((w & 1) == 1) pos.x -= 1f / size.x; if ((h & 1) == 1) pos.y += 1f / size.y; mSides[0] = rot * (new Vector3(x0, 0f, depth)) + pos; mSides[1] = rot * (new Vector3(0f, y1, depth)) + pos; mSides[2] = rot * (new Vector3(x1, 0f, depth)) + pos; mSides[3] = rot * (new Vector3(0f, y0, depth)) + pos; } else { mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0.5f, depth)); mSides[1] = cam.ViewportToWorldPoint(new Vector3(0.5f, 1f, depth)); mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 0.5f, depth)); mSides[3] = cam.ViewportToWorldPoint(new Vector3(0.5f, 0f, depth)); } if (relativeTo != null) { for (int i = 0; i < 4; ++i) mSides[i] = relativeTo.InverseTransformPoint(mSides[i]); } return mSides; } /// /// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right. /// static public Vector3[] GetWorldCorners (this Camera cam) { float depth = Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f); return cam.GetWorldCorners(depth, null); } /// /// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right. /// static public Vector3[] GetWorldCorners (this Camera cam, float depth) { return cam.GetWorldCorners(depth, null); } /// /// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right. /// static public Vector3[] GetWorldCorners (this Camera cam, Transform relativeTo) { return cam.GetWorldCorners(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), relativeTo); } /// /// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right. /// static public Vector3[] GetWorldCorners (this Camera cam, float depth, Transform relativeTo) { #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 if (cam.isOrthoGraphic) #else if (cam.orthographic) #endif { float os = cam.orthographicSize; float x0 = -os; float x1 = os; float y0 = -os; float y1 = os; Rect rect = cam.rect; Vector2 size = screenSize; float aspect = size.x / size.y; aspect *= rect.width / rect.height; x0 *= aspect; x1 *= aspect; // We want to ignore the scale, as scale doesn't affect the camera's view region in Unity Transform t = cam.transform; Quaternion rot = t.rotation; Vector3 pos = t.position; mSides[0] = rot * (new Vector3(x0, y0, depth)) + pos; mSides[1] = rot * (new Vector3(x0, y1, depth)) + pos; mSides[2] = rot * (new Vector3(x1, y1, depth)) + pos; mSides[3] = rot * (new Vector3(x1, y0, depth)) + pos; } else { mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0f, depth)); mSides[1] = cam.ViewportToWorldPoint(new Vector3(0f, 1f, depth)); mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 1f, depth)); mSides[3] = cam.ViewportToWorldPoint(new Vector3(1f, 0f, depth)); } if (relativeTo != null) { for (int i = 0; i < 4; ++i) mSides[i] = relativeTo.InverseTransformPoint(mSides[i]); } return mSides; } /// /// Convenience function that converts Class + Function combo into Class.Function representation. /// static public string GetFuncName (object obj, string method) { if (obj == null) return "<null>"; string type = obj.GetType().ToString(); int period = type.LastIndexOf('/'); if (period > 0) type = type.Substring(period + 1); return string.IsNullOrEmpty(method) ? type : type + "/" + method; } #if UNITY_EDITOR || !UNITY_FLASH /// /// Execute the specified function on the target game object. /// static public void Execute<T> (GameObject go, string funcName) where T : Component { T[] comps = go.GetComponents<T>(); foreach (T comp in comps) { #if !UNITY_EDITOR && (UNITY_WEBPLAYER || UNITY_FLASH || UNITY_METRO || UNITY_WP8 || UNITY_WP_8_1) comp.SendMessage(funcName, SendMessageOptions.DontRequireReceiver); #else MethodInfo method = comp.GetType().GetMethod(funcName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method != null) method.Invoke(comp, null); #endif } } /// /// Execute the specified function on the target game object and all of its children. /// static public void ExecuteAll<T> (GameObject root, string funcName) where T : Component { Execute<T>(root, funcName); Transform t = root.transform; for (int i = 0, imax = t.childCount; i < imax; ++i) ExecuteAll<T>(t.GetChild(i).gameObject, funcName); } /// /// Immediately start, update, and create all the draw calls from newly instantiated UI. /// This is useful if you plan on doing something like immediately taking a screenshot then destroying the UI. /// static public void ImmediatelyCreateDrawCalls (GameObject root) { ExecuteAll<UIWidget>(root, "Start"); ExecuteAll<UIPanel>(root, "Start"); ExecuteAll<UIWidget>(root, "Update"); ExecuteAll<UIPanel>(root, "Update"); ExecuteAll<UIPanel>(root, "LateUpdate"); } #endif #if UNITY_EDITOR static int mSizeFrame = -1; static System.Reflection.MethodInfo s_GetSizeOfMainGameView; static Vector2 mGameSize = Vector2.one; /// /// Size of the game view cannot be retrieved from Screen.width and Screen.height when the game view is hidden. /// static public Vector2 screenSize { get { int frame = Time.frameCount; if (mSizeFrame != frame || !Application.isPlaying) { mSizeFrame = frame; if (s_GetSizeOfMainGameView == null) { System.Type type = System.Type.GetType("UnityEditor.GameView,UnityEditor"); s_GetSizeOfMainGameView = type.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); } mGameSize = (Vector2)s_GetSizeOfMainGameView.Invoke(null, null); } return mGameSize; } } #else /// /// Size of the game view cannot be retrieved from Screen.width and Screen.height when the game view is hidden. /// static public Vector2 screenSize { get { return new Vector2(Screen.width, Screen.height); } } #endif } Assets/NGUI/Scripts/Internal/NGUITools.cs(57,51): error CS0619: UnityEngine.RuntimePlatform.WindowsWebPlayer' is obsolete: WebPlayer export is no longer supported in Unity 5.4+.'

// 重新分配活动弹幕的轨道 private void ReassignActiveDanmus() { if (activeDanmus == null || activeDanmus.Count == 0) return; if (trackPositions == null || trackPositions.Length == 0) return; // 记录每条轨道上最后一个弹幕的右边界 float[] trackLastRight = new float[trackPositions.Length]; for (int i = 0; i < trackLastRight.Length; i++) trackLastRight[i] = -containerWidth; // 按X坐标从右到左排序,右侧弹幕优先分配轨道 activeDanmus.Sort((a, b) => b.transform.localPosition.x.CompareTo(a.transform.localPosition.x)); foreach (var danmu in activeDanmus.ToArray()) { if (!danmu.IsMove) continue; float danmuWidth = danmu.GetWidth(); float danmuX = danmu.transform.localPosition.x; int assigned = -1; // 只分配不会重叠的轨道 for (int t = 0; t < trackPositions.Length; t++) { if (danmuX >= trackLastRight[t] + config.minHorizontalGap) { assigned = t; break; } } if (assigned == -1) { // 没有可用轨道,回收弹幕 ReturnDanmuToPool(danmu); continue; } // 分配轨道并调整Y坐标,X坐标保持不变 danmu.assignedTrack = assigned; Vector2 pos = danmu.transform.localPosition; pos.y = trackPositions[assigned]; danmu.transform.localPosition = pos; float rightEdge = danmuX + danmuWidth; if (rightEdge > trackLastRight[assigned]) trackLastRight[assigned] = rightEdge; } }在当轨道变少时,自动减少屏幕上的弹幕数量,避免弹幕在新轨道上堆叠或重叠,需要切换显示区域或轨道变少时,弹幕数量会自动减少到不会重叠的合理数量,但不会只剩一条弹幕,每条轨道也可以有多条弹幕,同时切换显示数量以后能够平滑的过度,我的意思是指他是在当前屏幕能看到滚动弹幕的区域来重新分配弹幕在轨道上的位置,不是像现在的代码一样回到初始位置

不要改进,把using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class UIDraggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { [Header(“拖拽设置”)] public Sprite dragSprite; public Color dragColor = new Color(1, 1, 1, 0.7f); [Header("放置设置")] public RectTransform dropZone; [Header("生成设置")] public GameObject spawnPrefab; public Transform spawnParent; public Vector3 spawnScale = Vector3.one; public bool showPrefabInitially = false; public AudioClip clickSound; private Canvas canvas; private RectTransform canvasRectTransform; private GameObject draggingObject; private RectTransform draggingObjectRect; private Image draggingImage; private AudioSource audioSource; private void Awake() { canvas = GetComponentInParent<Canvas>(); if (canvas != null) { canvasRectTransform = canvas.GetComponent<RectTransform>(); } audioSource = gameObject.AddComponent<AudioSource>(); audioSource.playOnAwake = false; } public void OnBeginDrag(PointerEventData eventData) { draggingObject = new GameObject("DraggingObject"); draggingObject.transform.SetParent(canvas.transform, false); draggingObject.transform.SetAsLastSibling(); draggingImage = draggingObject.AddComponent<Image>(); draggingImage.sprite = dragSprite != null ? dragSprite : GetComponent<Image>().sprite; draggingImage.color = dragColor; draggingImage.raycastTarget = false; draggingObjectRect = draggingObject.GetComponent<RectTransform>(); draggingObjectRect.sizeDelta = GetComponent<RectTransform>().sizeDelta; draggingObjectRect.pivot = GetComponent<RectTransform>().pivot; SetDraggedPosition(eventData); } public void OnDrag(PointerEventData eventData) { if (draggingObject != null) { SetDraggedPosition(eventData); if (dropZone != null) { bool insideDropZone = IsInsideRectTransform(draggingObjectRect, dropZone); draggingImage.color = insideDropZone ? new Color(0.5f, 1f, 0.5f, dragColor.a) : new Color(1f, 0.5f, 0.5f, dragColor.a); } } } public void OnEndDrag(PointerEventData eventData) { if (draggingObject == null) return; bool withinCanvas = IsWithinCanvas(eventData.position); bool inDropZone = dropZone == null || IsInsideRectTransform(draggingObjectRect, dropZone); if (withinCanvas && inDropZone) { GameObject spawnedObject = CreateSpawnedObject(draggingObjectRect.position); if (DragDropManager.Instance != null) { DragDropManager.Instance.RecordPlacement(spawnedObject); } OnValidDrop(spawnedObject); } Destroy(draggingObject); } private GameObject CreateSpawnedObject(Vector3 position) { GameObject spawnedObj = new GameObject("SpawnedObject"); spawnedObj.transform.SetParent(spawnParent != null ? spawnParent : canvas.transform); spawnedObj.transform.position = position; spawnedObj.transform.localScale = Vector3.one; // 添加基础UI组件 Image img = spawnedObj.AddComponent<Image>(); img.color = Color.white; // 添加连接功能 spawnedObj.AddComponent<ConnectableObject>(); // 生成Prefab作为子物体 if (spawnPrefab != null) { GameObject prefabInstance = Instantiate(spawnPrefab, spawnedObj.transform); prefabInstance.transform.localScale = spawnScale; prefabInstance.SetActive(showPrefabInitially); } return spawnedObj; } protected virtual void OnValidDrop(GameObject spawnedObject) { // 可被子类扩展 } // ... [保留其他辅助方法] ... }这个代码修改进第二次提供的完整代码中

using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic; namespace UUI { public partial class DlgTest : DlgBase<DlgTest> { protected override void OnInitFinished() { //Debug.Log("---OnInitFinished---"); TransformContent_X.GetChild(0).GetComponent<Button>().onClick.AddListener(OnButtonClick); } public override void OnUpdate() { this.SetVisible(true); } protected override void OnShow() { //Debug.Log("---OnShow---"); } public override void SetVisible(bool bVisible, object param = null) { base.SetVisible(bVisible, param); //chongxieluoji TransformContent_X.GetChild(0).GetComponent<Button>().onClick.AddListener(OnButtonClick); ButtonDfkjsldjfl_X.onClick.AddListener(OnButtonClick); } void OnButtonClick() { Debug.Log("Button Dfkjsldjfl_X 被点击"); Transform parentTransform = ButtonDfkjsldjfl_X.transform.parent; if (parentTransform == null) { Debug.LogError("ButtonDfkjsldjfl_X has no parent!"); } // 复制当前按钮 Button newButton = ButtonDfkjsldjfl_X; // 设置新按钮的父对象为同一个父对象 newButton.transform.SetParent(parentTransform); // 设置新按钮在兄弟节点中的位置:在当前按钮的下一个位置(这样就会在下方) int currentIndex = ButtonDfkjsldjfl_X.transform.GetSiblingIndex(); newButton.transform.SetSiblingIndex(currentIndex + 1); // 刷新布局(如果父对象有VerticalLayoutGroup,需要刷新) // 首先检查父对象是否有布局组 LayoutGroup layoutGroup = parentTransform.GetComponent<LayoutGroup>(); if (layoutGroup != null) { LayoutRebuilder.ForceRebuildLayoutImmediate(parentTransform.GetComponent<RectTransform>()); } } } } 这个代码没有实现上述需求,怎么改

最新推荐

recommend-type

永磁同步电机全速域无传感器控制技术及其应用 加权切换法

内容概要:本文详细探讨了永磁同步电机(PMSM)在全速域范围内的无传感器控制技术。针对不同的速度区间,提出了三种主要的控制方法:零低速域采用高频脉振方波注入法,通过注入高频方波信号并处理产生的交互信号来估算转子位置;中高速域则使用改进的滑膜观测器,结合连续的sigmoid函数和PLL锁相环,实现对转子位置的精确估计;而在转速切换区域,则采用了加权切换法,动态调整不同控制方法的权重,确保平滑过渡。这些方法共同实现了电机在全速域内的高效、稳定运行,减少了对传感器的依赖,降低了系统复杂度和成本。 适合人群:从事电机控制系统设计、研发的技术人员,尤其是关注永磁同步电机无传感器控制领域的研究人员和技术爱好者。 使用场景及目标:适用于需要优化电机控制系统,减少硬件成本和提升系统可靠性的应用场景。目标是在不依赖额外传感器的情况下,实现电机在各种速度条件下的精准控制。 其他说明:文中引用了多篇相关文献,为每种控制方法提供了理论依据和实验验证的支持。
recommend-type

langchain4j-spring-boot-starter-0.29.1.jar中文文档.zip

1、压缩文件中包含: 中文文档、jar包下载地址、Maven依赖、Gradle依赖、源代码下载地址。 2、使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 3、特殊说明: (1)本文档为人性化翻译,精心制作,请放心使用; (2)只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; (3)不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 4、温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件。 5、本文件关键字: jar中文文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册。
recommend-type

4节点光储直流微网:基于多目标控制与多智能体一致性的光伏MPPT与储能双向DCDC优化

内容概要:本文介绍了一个15kW、400V级的四节点光储直流微网系统的设计与实现。该系统采用多目标控制、多智能体一致性及二次优化技术,旨在实现高效的能量管理和稳定的系统运行。具体而言,光伏MPPT采用粒子群算法以最大化太阳能利用率;储能系统的双向DCDC变换器则运用了多种控制策略,如电流内环的模型预测控制、电压环的分布式控制、初级控制的下垂策略以及二次控制的差异性和电压补偿策略。这些措施共同确保了直流母线电压的恢复和储能系统的SoC一致控制。 适合人群:从事电力电子、新能源技术和微网系统研究的专业人士,尤其是关注光储直流微网系统设计与优化的研究人员和技术人员。 使用场景及目标:适用于需要深入了解光储直流微网系统设计原理及其控制策略的应用场合,如科研机构、高校实验室、电力公司等。目标是为相关领域的研究人员提供理论依据和技术支持,促进微网技术的发展。 其他说明:文中详细讨论了各部分的具体实现方法和技术细节,对于希望深入理解光储直流微网系统运作机制的读者非常有帮助。
recommend-type

Webdiy.net新闻系统v1.0企业版发布:功能强大、易操作

标题中提到的"Webdiy.net新闻系统 v1.0 企业版"是一个针对企业级应用开发的新闻内容管理系统,是基于.NET框架构建的。从描述中我们可以提炼出以下知识点: 1. **系统特性**: - **易用性**:系统设计简单,方便企业用户快速上手和操作。 - **可定制性**:用户可以轻松修改网站的外观和基本信息,例如网页标题、页面颜色、页眉和页脚等,以符合企业的品牌形象。 2. **数据库支持**: - **Access数据库**:作为轻量级数据库,Access对于小型项目和需要快速部署的场景非常合适。 - **Sql Server数据库**:适用于需要强大数据处理能力和高并发支持的企业级应用。 3. **性能优化**: - 系统针对Access和Sql Server数据库进行了特定的性能优化,意味着它能够提供更为流畅的用户体验和更快的数据响应速度。 4. **编辑器功能**: - **所见即所得编辑器**:类似于Microsoft Word,允许用户进行图文混排编辑,这样的功能对于非技术人员来说非常友好,因为他们可以直观地编辑内容而无需深入了解HTML或CSS代码。 5. **图片管理**: - 新闻系统中包含在线图片上传、浏览和删除的功能,这对于新闻编辑来说是非常必要的,可以快速地为新闻内容添加相关图片,并且方便地进行管理和更新。 6. **内容发布流程**: - **审核机制**:后台发布新闻后,需经过审核才能显示到网站上,这样可以保证发布的内容质量,减少错误和不当信息的传播。 7. **内容排序与类别管理**: - 用户可以按照不同的显示字段对新闻内容进行排序,这样可以突出显示最新或最受欢迎的内容。 - 新闻类别的动态管理及自定义显示顺序,可以灵活地对新闻内容进行分类,方便用户浏览和查找。 8. **前端展示**: - 系统支持Javascript前端页面调用,这允许开发者将系统内容嵌入到其他网页或系统中。 - 支持iframe调用,通过这种HTML元素可以将系统内容嵌入到网页中,实现了内容的跨域展示。 9. **安全性**: - 提供了默认的管理账号和密码(webdiy / webdiy.net),对于企业应用来说,这些默认的凭证需要被替换,以保证系统的安全性。 10. **文件结构**: - 压缩包文件名称为"webdiynetnews",这可能是系统的根目录名称或主要安装文件。 11. **技术栈**: - 系统基于ASP.NET技术构建,这表明它使用.NET框架开发,并且可以利用.NET生态中的各种库和工具来实现功能的扩展和维护。 在实施和部署这样的系统时,企业可能还需要考虑以下方面: - **可扩展性**:随着业务的增长,系统应该能容易地扩展,以支持更多的用户和内容。 - **安全性**:除了更改为安全的管理员凭证外,还需考虑防止SQL注入、XSS攻击等网络安全问题。 - **备份和恢复**:定期备份数据库和内容是很重要的,以防数据丢失或需要恢复到先前的状态。 - **多用户和权限管理**:企业环境可能需要多级用户权限设置,以适应不同的团队和角色。 - **SEO优化**:系统应支持良好的搜索引擎优化实践,以便于内容在搜索引擎中的排名和发现。 - **移动适应性**:由于移动设备的广泛使用,系统应具备良好的响应式设计,以提供良好的移动用户体验。 根据描述,该系统似乎是一个成熟的解决方案,适用于需要快速搭建新闻网站的企业用户,但同时也应该注意定期的维护和更新,以确保系统的稳定性和安全性。
recommend-type

【Windows 11用户的福音】:一步到位解决GX Works2安装问题,让兼容性不再是问题!

# 1. GX Works2简介与Windows 11兼容性问题 ## 简介GX Works2 GX Works2是由三菱电机开发的一款针对其PLC(可编程逻辑控制器)产品的编程和调试软件。该软件以其直观的用户界面和强大的编程功能闻名于工业自动化领域,支持从简单的逻辑控制到复杂的系统集成项目。随着Windows操作系统的迭代升级,尤其是新推
recommend-type

电磁加热双边谐振和单边谐振的区别

<think>我们正在处理关于电磁加热技术中双边谐振与单边谐振的工作原理及区别的问题。 首先,需要明确用户意图是了解这两种谐振方式的区别以及它们的工作原理。 我们将通过以下步骤进行: 1. 调用网络搜索工具,检索关于电磁加热中双边谐振和单边谐振的信息。 2. 整合检索到的内容,按照要求生成回答,包括工作原理和区别,并组织成多个方法或步骤(但避免使用步骤词汇,用换行分隔)。 3. 在回答中,如果有公式或代码,按照指定格式处理。 4. 最后,添加相关问题部分。 注意:避免使用第一人称,避免步骤词汇,引用内容不集中末尾,而是融入回答中。 根据搜索,电磁加热中的谐振通常指的是感应加
recommend-type

EnvMan源代码压缩包内容及功能解析

根据给定文件信息,我们需要生成关于“EnvMan-source.zip”这一压缩包的知识点。首先,由于提供的信息有限,我们无法直接得知EnvMan-source.zip的具体内容和功能,但可以通过标题、描述和标签中的信息进行推断。文件名称列表只有一个“EnvMan”,这暗示了压缩包可能包含一个名为EnvMan的软件或项目源代码。以下是一些可能的知识点: ### EnvMan软件/项目概览 EnvMan可能是一个用于环境管理的工具或框架,其源代码被打包并以“EnvMan-source.zip”的形式进行分发。通常,环境管理相关的软件用于构建、配置、管理和维护应用程序的运行时环境,这可能包括各种操作系统、服务器、中间件、数据库等组件的安装、配置和版本控制。 ### 源代码文件说明 由于只有一个名称“EnvMan”出现在文件列表中,我们可以推测这个压缩包可能只包含一个与EnvMan相关的源代码文件夹。源代码文件夹可能包含以下几个部分: - **项目结构**:展示EnvMan项目的基本目录结构,通常包括源代码文件(.c, .cpp, .java等)、头文件(.h, .hpp等)、资源文件(图片、配置文件等)、文档(说明文件、开发者指南等)、构建脚本(Makefile, build.gradle等)。 - **开发文档**:可能包含README文件、开发者指南或者项目wiki,用于说明EnvMan的功能、安装、配置、使用方法以及可能的API说明或开发者贡献指南。 - **版本信息**:在描述中提到了版本号“-1101”,这表明我们所见的源代码包是EnvMan的1101版本。通常版本信息会详细记录在版本控制文件(如ChangeLog或RELEASE_NOTES)中,说明了本次更新包含的新特性、修复的问题、已知的问题等。 ### 压缩包的特点 - **命名规范**:标题、描述和标签中的一致性表明这是一个正式发布的软件包。通常,源代码包的命名会遵循一定的规范,如“项目名称-版本号-类型”,在这里类型是“source”。 - **分发形式**:以.zip格式的压缩包进行分发,是一种常见的软件源代码分发方式。虽然较现代的版本控制系统(如Git、Mercurial)通常支持直接从仓库克隆源代码,但打包成zip文件依然是一种便于存储和传输的手段。 ### 可能的应用场景 - **开发环境配置**:EnvMan可能是用于创建、配置和管理开发环境的工具,这种工具在开发人员设置新的开发机或新的项目环境时非常有用。 - **自动化部署**:EnvMan可能包含自动化部署环境的脚本或命令,使得部署流程变得快捷且高效。 - **监控与维护**:作为环境管理工具,EnvMan可能还支持对环境的监控功能,包括系统资源监控、服务状态检查等,以保证生产环境的稳定性。 ### 总结 尽管以上知识点是基于有限的信息进行的假设性推论,但EnvMan-source.zip包可能是一个用于环境管理的软件或项目的源代码包。该软件或项目可能包含构建和部署自动化环境的能力,以及对运行时环境的监控和维护。文件命名的一致性暗示这是一个正式的版本发布。如果要深入了解EnvMan的功能与用法,建议直接查看压缩包中的文档或源代码注释。同时,考虑到源代码的开发,我们还应该探究该项目所使用的技术栈、编程语言以及版本控制工具等,这将有助于进一步了解EnvMan的技术细节。
recommend-type

【Windows 11终极解决方案】:彻底攻克GX Works2安装中难缠的.Net Framework 3.5障碍!

# 1. Windows 11与GX Works2简介 ## 1.1 Windows 11操作系统概览 Windows 11,作为微软最新的操作系统,不仅仅提供了一种现代的用户体验,而且加强了在企业环境中的安全性与生产力工具。其引入了全新的界面设计、改进的多任务处理以及对Android应用的支持,使它成为IT专业人
recommend-type

贝叶斯gmm

<think>首先,用户的问题是关于贝叶斯高斯混合模型(Bayesian Gaussian Mixture Model, BGMM)的原理和应用。我需要根据系统指令来构建回答。 系统指令包括: - 所有行内数学表达式使用 `$...$` 格式。 - 独立公式使用 `$$...$$` 格式并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 在回答中引用的段落末尾自然地添加引用标识,如 `[^1]`。 - 回答结构清晰,帮助用户逐步解决问题。 - 保证回答真实可靠。 参考提供的引用: - 引用[1]:讨论了高斯混合模型在机器学习中的应用,包括其优点和挑战。 -
recommend-type

威海卫国旅游网美化版网站建设意向表下载

根据提供的文件信息,我们可以提取以下知识点: 1. 网站建设意向表概念: 网站建设意向表是指在网站开发过程中,客户或项目负责人填写的一份表单,用以明确表达网站建设的需求、目标、功能、风格偏好等关键信息。它是项目开发前期沟通的载体,确保开发团队能够准确理解客户需求并据此进行网站设计和功能实现。 2. 美化版的含义: 美化版通常指的是对原有产品、设计或界面进行视觉上的改进,使之更加吸引人和用户体验更佳。在网站建设的上下文中,美化版可能指对网站的设计元素、布局、色彩搭配等进行更新和优化,从而提高网站的美观度和用户交互体验。 3. 代码和CSS的优化: 代码优化:指的是对网站的源代码进行改进,包括但不限于提高代码的执行效率、减少冗余、提升可读性和可维护性。这可能涉及代码重构、使用更高效的算法、减少HTTP请求次数等技术手段。 CSS优化:层叠样式表(Cascading Style Sheets, CSS)是一种用于描述网页呈现样式的语言。CSS优化可能包括对样式的简化、合并、压缩,使用CSS预处理器、应用媒体查询以实现响应式设计,以及采用更高效的选择器减少重绘和重排等。 4. 网站建设实践: 网站建设涉及诸多实践,包括需求收集、网站规划、设计、编程、测试和部署。其中,前端开发是网站建设中的重要环节,涉及HTML、CSS和JavaScript等技术。此外,还需要考虑到网站的安全性、SEO优化、用户体验设计(UX)、交互设计(UI)等多方面因素。 5. 文件描述中提到的威海卫国旅游网: 威海卫国旅游网可能是一个以威海地区旅游信息为主题的网站。网站可能提供旅游景点介绍、旅游服务预订、旅游攻略分享等相关内容。该网站的这一项目表明,他们关注用户体验并致力于提供高质量的在线服务。 6. 文件标签的含义: 文件标签包括“下载”、“源代码”、“源码”、“资料”和“邮件管理类”。这些标签说明该压缩文件中包含了可以下载的资源,具体内容是网站相关源代码以及相关的开发资料。另外,提到“邮件管理类”可能意味着在网站项目中包含了用于处理用户邮件订阅、通知、回复等功能的代码或模块。 7. 压缩文件的文件名称列表: 该文件的名称为“网站建设意向表 美化版”。从文件名称可以推断出该文件是一个表单,用于收集网站建设相关需求,且经过了视觉和界面的改进。 综合上述内容,可以得出结论,本表单文件是一个为特定网站建设项目设计的需求收集工具,经过技术优化并美化了用户界面,旨在提升用户体验,并且可能包含了邮件管理功能,方便网站运营者与用户进行沟通。该文件是一份宝贵资源,尤其是对于需要进行网站建设或优化的开发者来说,可以作为参考模板或直接使用。