DogInitialize.cs 3.1 KB

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