DogInitialize.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 = EnviromentSetting.maxDogQty; // 限制最大狗的数量
  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. {
  49. dogResource = Resources.Load<GameObject>("Dog/Breed/shibaInu"); // 默认读取,防止后端传入数据错误
  50. }
  51. GameObject dog = Instantiate(dogResource);
  52. if (!string.IsNullOrWhiteSpace(dogDisplayName))
  53. {
  54. dog.name = dogDisplayName;
  55. }
  56. else
  57. {
  58. dog.name = puppy.dog_name;
  59. }
  60. if (dog != null)
  61. {
  62. GameObject dogL2;
  63. try
  64. {
  65. dogL2 = dog.transform.Find(puppy.breed).gameObject;
  66. }
  67. catch
  68. {
  69. dogL2 = dog.transform.Find("shibaInu").gameObject;
  70. }
  71. Renderer renderer = dogL2.GetComponent<Renderer>();
  72. //Texture skin = Resources.Load<Texture>("Dog/Skin/" + puppy.breed + "/" + puppy.skin);
  73. Material mat = Resources.Load<Material>("Dog/Skin/" + puppy.breed + "/" + puppy.skin);
  74. if (mat == null)
  75. {
  76. mat = Resources.Load<Material>("Dog/Skin/shibaInu/amber"); // 默认读取,防止后端传入数据错误
  77. }
  78. if (mat != null && renderer != null)
  79. {
  80. //renderer.material.mainTexture = skin;
  81. renderer.material = mat;
  82. }
  83. }
  84. dog.transform.localPosition = position;
  85. dog.transform.localRotation = Quaternion.Euler(rotation);
  86. dog.transform.localScale = scale;
  87. dog.tag = "dog"; // 设置tag为dog,方便后续查找
  88. }
  89. }
  90. }