
Unity 制作黑暗之光第二章的筆記 ,不足或錯誤請聯系部落客及時更改,謝謝。
第二章 角色建立
1.角色建立UI界面搭建
建立Sprite元件
建立取名為Title标題的Sprite元件
建立取名為Next和Prev的Sprite元件
分别為Next和添加Box Collider和Button Script與Play Sound元件
并調整他們的屬性
建立取名為EnterName的Sprite元件并添加輸入框預設物
添加Ok按鈕并添加元件
調整它們的布局大小
2.設計Ider狀态的兩個角色
設定兩個人物角色模型
添加Ider動畫狀态并存為預制體
3.控制所有角色的建立顯示與切換
建立名為CharacterCreation的GameObject,放置于人物模型初始的位置
添加CharacterCreation代碼
1 public GameObject[] characterPrefabs;//存儲所有角色的數組
2 private GameObject[] characterGameObjects;//建立出來之後的遊戲物體
3 private int selectedIndex = 0;//目前選擇的索引
4 private int length;//所有角色的個數
5 /// <summary>
6 /// 初始化
7 /// </summary>
8 void Start()
9 {
10 length = characterPrefabs.Length;
11 characterGameObjects = new GameObject[length];
12 for (int i = 0; i < length; i++)
13 {
14 characterGameObjects[i] = GameObject.Instantiate(characterPrefabs[i], transform.position, transform.rotation) as GameObject;
15 }
16 UpdateCharacterShow();
17 }
18 /// <summary>
19 /// 更新所有角色的顯示
20 /// </summary>
21 void UpdateCharacterShow()
22 {
23 characterGameObjects[selectedIndex].SetActive(true);
24 for (int i = 0; i < length; i++)
25 {
26 if (i != selectedIndex)
27 {
28 characterGameObjects[i].SetActive(false);//把未選擇的角色設定為隐藏
29 }
30 }
31 }
32 /// <summary>
33 /// 點選了上一個按鈕
34 /// </summary>
35 public void OnPrevButtonClick()
36 {
37 selectedIndex--;
38 if (selectedIndex == -1)
39 {
40 selectedIndex = length - 1;
41 }
42 UpdateCharacterShow();
43 }
44 /// <summary>
45 /// 點選了下一個按鈕
46 /// </summary>
47 public void OnNextButtonClick()
48 {
49 selectedIndex++;
50 selectedIndex %= length;
51 UpdateCharacterShow();
52 }
綁定按鈕On Click點選
4.名稱的輸入和場景的切換
寫入CharacterCreation指派并綁定Ok按鈕點選事件
1 public UIInput nameInput;//用來得到輸入的文本
2
3 public void OnOkButtonClick()
4 {
5 PlayerPrefs.SetInt("SelectedCharacterIndex", selectedIndex);//存儲選擇的角色
6 PlayerPrefs.SetString("name", nameInput.value);//存儲輸入的名字
7 //加載下一個場景
8 }
關于Unity黑暗之光的其他筆記
Unity 黑暗之光 第一章
Unity 黑暗之光 第二章
Unity 黑暗之光 第三章
Unity 黑暗之光 第四章