DogInitialize.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using UnityEngine;
  2. /* 本类用于动态加载狗
  3. * 初始化狗的基础模型和颜色
  4. * 场景中特殊的components 需要在场景单独的程序中加载
  5. * 狗的breed和skin大小写需要注意
  6. * 本代码控制最大显示狗的数量,变量:maxDogQty
  7. * 本代码需要挂在到场景中任意Game Object下。建议挂载在Player下
  8. */
  9. public class DogInitialize: MonoBehaviour {
  10. public Vector3 position, rotation, scale = new Vector3(1,-10,1) ; // 狗初始化位置
  11. public string dogDisplayName; // 狗的id指的是调用用户拥有的狗的id dogName是狗在场景中的显示名
  12. private DogProperty dogProperty;
  13. public bool loadAllDogs = false; // 是否读取所有的狗,如果否就读取focusDog,否则读取全部狗
  14. // Start is called once before the first execution of Update after the MonoBehaviour is created
  15. void Start()
  16. {
  17. int maxDogQty = 3; // 限制最大狗的数量
  18. while (UserProperty.dogs.Count > maxDogQty)
  19. {
  20. UserProperty.dogs.RemoveAt(UserProperty.dogs.Count - 1);
  21. }
  22. if (loadAllDogs)
  23. {
  24. foreach (var dog in UserProperty.dogs)
  25. {
  26. dogProperty = dog;
  27. InitialDog();
  28. }
  29. }
  30. else
  31. {
  32. dogProperty = UserProperty.dogs[GameData.focusDog];
  33. InitialDog();
  34. }
  35. }
  36. // Update is called once per frame
  37. //void Update()
  38. //{
  39. //}
  40. // 初始化狗,并显示在屏幕上
  41. public void InitialDog()
  42. {
  43. if (this.dogProperty != null)
  44. {
  45. var puppy = this.dogProperty;
  46. GameObject dogResource = Resources.Load<GameObject>("Dog/Breed/" + puppy.breed);
  47. if (dogResource == null) {
  48. dogResource = Resources.Load<GameObject>("Dog/Breed/shibaInu"); // 默认读取,防止后端传入数据错误
  49. }
  50. GameObject dog = Instantiate(dogResource);
  51. if (!string.IsNullOrWhiteSpace(dogDisplayName))
  52. {
  53. dog.name = dogDisplayName;
  54. }
  55. else
  56. {
  57. dog.name = puppy.dog_name;
  58. }
  59. if (dog != null)
  60. {
  61. GameObject dogL2;
  62. try
  63. {
  64. dogL2 = dog.transform.Find(puppy.breed).gameObject;
  65. }
  66. catch
  67. {
  68. dogL2 = dog.transform.Find("shibaInu").gameObject;
  69. }
  70. Renderer renderer = dogL2.GetComponent<Renderer>();
  71. //Texture skin = Resources.Load<Texture>("Dog/Skin/" + puppy.breed + "/" + puppy.skin);
  72. Material mat = Resources.Load<Material>("Dog/Skin/" + puppy.breed + "/" + puppy.skin);
  73. if (mat == null)
  74. {
  75. mat = Resources.Load<Material>("Dog/Skin/shibaInu/amber"); // 默认读取,防止后端传入数据错误
  76. }
  77. if (mat != null && renderer != null)
  78. {
  79. //renderer.material.mainTexture = skin;
  80. renderer.material = mat;
  81. }
  82. }
  83. dog.transform.localPosition = position;
  84. dog.transform.localRotation = Quaternion.Euler(rotation);
  85. dog.transform.localScale = scale;
  86. }
  87. }
  88. }