var playersSpecifics = GameObject.FindGameObjectWithTag("PlayersSpecifics"); if (playersSpecifics == null) { Debug.LogError("PlayersSpecifics not found, please add it to the scene"); return; }
var playerSpecific = playersSpecifics.transform.GetChild(_playerIndex).gameObject; if (playersSpecifics == null) { Debug.LogWarning("PlayerSpecific: " + _playerIndex + " not found, using default(0)"); playerSpecific = playersSpecifics.transform.GetChild(0).gameObject; }
// Copy all components from the playerSpecific prefab to this instance { transform.position = playerSpecific.transform.position; transform.rotation = playerSpecific.transform.rotation; transform.localScale = playerSpecific.transform.localScale;
foreach (var component in playerSpecific.GetComponents<Component>()) { if (component is Transform) continue; CopyComponent(component, gameObject); } }
privatestaticvoidCopyComponent(Component original, GameObject destination) { var type = original.GetType(); if (destination.TryGetComponent(type, outvar copyComponent)) Debug.Log("Component already exists: " + type.Name); else copyComponent = destination.AddComponent(type);
foreach (var field in type.GetFields(BindingFlags.Instance)) { Debug.Log("Copying field from " + original.GetType().Name + ": " + field.Name); field.SetValue(copyComponent, field.GetValue(original)); }
foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (!property.CanWrite || property.Name == "name") continue;
综上所述,之后只需要把通用的直接挂载在 Player Perefab,把特殊的分别在每个 PlayerSpecific 就行了,比如之后有不同的武器系统,都实现起来很方便。
Field and Property
Field 和 Property 是 C# 中两种不同的成员变量定义方式,如下。
1 2 3 4 5 6 7 8 9 10 11 12
publicclassPerson { // Private field privatestring _name;
// Property publicstring Name { get { return _name; } // Returns the value of the private field set { _name = value; } // Sets the value of the private field } }