代码控制人物选择角色

 1    public GameObject[] characterPrefabs;//在外部赋值的角色
 2     private GameObject[] characterGameObjects;//在代码中赋值的角色
 3     private int selectIndex = 0; //当前选择的角色
 4     private int length; //所有可供选择的角色的个数
 5 
 6 
 7     private void Start()
 8     {
 9         length = characterPrefabs.Length;
10         characterGameObjects = new GameObject[length];
11         for (int i = 0; i < length; i++)
12         {
13             characterGameObjects[i] =GameObject.Instantiate(characterPrefabs[i], transform.position, transform.rotation) as GameObject;
14         }
15         UpdateCharacterShow();
16     }
17 
18     //更新所有角色的显示
19     void UpdateCharacterShow()
20     {
21         characterGameObjects[selectIndex].SetActive(true);
22         //把未选择的角色设置为隐藏
23         for (int i = 0; i < length; i++)
24         {
25             if (i != selectIndex)
26             {
27                 characterGameObjects[i].SetActive(false);
28             }
29         }
30 
31     }
32 
33     //点击下一个按钮
34     public void OnNextButtonClick()
35     {    
36         selectIndex++;
37         //跟length求余 超出范围索引为0
38         selectIndex %= length;
39         UpdateCharacterShow();
40 
41     }
42 
43     //点击上一个按钮
44     public void OnPrevButtonClick()
45     {
46         selectIndex--;
47         //如果等于负1,就循环到最大的索引
48         if (selectIndex == -1)
49         {            
50             selectIndex = length - 1;
51         }
52         UpdateCharacterShow();
53     }

 

posted on 2018-10-29 10:28  追求LPY  阅读(461)  评论(0编辑  收藏  举报