public SerializedComponentReference(PrefabEntity entity, Component component) : base(entity) { _type = component.GetType(); var components = entity.GetComponents(_type); for (int i = 0; i < components.Length; i++) { if (components[i] == component) { _componentIndex = i; break; } } }
/** * Called after an object is deserialized. This interates through components and sets the modified values, * while simultaneously rebuilding modifiedValues so that the keys point to actual component objects. */ public void ApplyDifferences(PrefabEntity target) { if (_keys == null || _keys.Count < 1) { return; } if (_values.Count != _keys.Count) { Debug.LogErrorFormat("Invalid keys count {0} to values count {1}", _keys.Count, _values.Count); return; } _modifiedValues = new Dictionary <Component, Dictionary <string, object> >(); var limit = _keys.Count; // if a component has multiple instances on an object, this will make sure that they remain distinct (probably) var dupComponents = new Dictionary <Type, int>(); for (var i = 0; i < limit; i++) { var components = target.GetComponents(_keys[i]); if (dupComponents.ContainsKey(_keys[i])) { dupComponents[_keys[i]]++; } else { dupComponents.Add(_keys[i], 0); } var index = MathEx.Min(dupComponents[_keys[i]], components.Length - 1); if (index >= components.Length || index < 0) { Debug.LogErrorFormat("Index {0} on {1} out of range", index, target.name); continue; } if (i >= _values.Count) { Debug.LogErrorFormat("Values Index {0} on {1} out of range", i, target.name); continue; } var component = components[index]; _modifiedValues.Add(component, _values[i]); foreach (var kvp in _values[i]) { var key = kvp.Key; if (!key.Contains("Array")) { ReflectionHelper.SetValue(components[index], key, kvp.Value); continue; } var parts = key.Split('.'); key = parts[0]; for (int p = 0; p < parts.Length; p++) { if (p < 2) { continue; } var part = parts[p]; if (part == "size") { int newSize; if (int.TryParse(kvp.Value as string, out newSize)) { ReflectionHelper.ResizeArray(components[index], key, newSize); break; } } if (part.Contains("data")) { var indexString = part.Substring(5, 1); int arrayIdx; if (int.TryParse(indexString, out arrayIdx)) { ReflectionHelper.SetArrayObj(components[index], key, arrayIdx, kvp.Value); break; } } } } } }