у меня есть класс давай сделаем через tryadd public class TrackerPanel : MonoBehaviour {…
- User
у меня есть класс давай сделаем через tryadd public class TrackerPanel : MonoBehaviour { [SerializeField] private TrackerFrame trackerFramePrefab; [SerializeField] private RectTransform contentPanel;
codeprivate Dictionary<int, TrackerFrame> trackers = new Dictionary<int, TrackerFrame>(); public void InitializeTrackers(int trackerNumbers) { for (int i = 1; i <= trackerNumbers; i++) { if (!trackers.ContainsKey(i)) { var tracker = Instantiate(trackerFramePrefab, contentPanel); tracker.InitializeTracker(i); trackers.Add(i, tracker); } } } public void UpdateTrackerText(int trackerNumber, int pulse, int spo2) { if (trackers.TryGetValue(trackerNumber, out var tracker)) { tracker.UpdateTextTracker(pulse, spo2); } }}
- Assistant
To make use of the
TryAddmethod, which was introduced in .NET Core 3.0 and is not available in earlier versions, you'll need to be using a version of .NET whereDictionary<TKey, TValue>supports this method (such as in recent versions of Unity, which include newer versions of the .NET runtime).Here's how you could refactor your
InitializeTrackersmethod usingTryAdd. This method will attempt to add the key-value pair to the dictionary and returntrueif successful, orfalseif a key-value pair with the same key already exists:csharppublic void InitializeTrackers(int trackerNumbers) { for (int i = 1; i <= trackerNumbers; i++) { if (trackers.TryAdd(i, Instantiate(trackerFramePrefab, contentPanel))) { trackers[i].InitializeTracker(i); } } }