进入游戏后,我们经常会进入角色选择的界面。通常是左右两个按钮可以更改角色供玩家选择。对于这种界面我们通常使用数据持久化将角色信息存储起来。
接下来的笔记中,我将使用自带的数据持久化系统对其进行操作,实现角色的选择页面。(后续会更新xml系列的文件配置方法实现角色的选择,敬请期待!)
以下是使用Unity进行操作,UI是使用NGUI,下面的完整代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// 一个用于控制人物创建的基类
/// </summary>
public class CharacterCreation : MonoBehaviour
{
//用于关联预设体
public GameObject[] characterPrefabs;
//创建个数
private GameObject[] characterGameObjects;
private int selectedIndex = 0;
//选择角色个数
private int length;
//关联上一个按钮的点击
public UIButton btnLast;
//关联下一个按钮的点击
public UIButton btnNext;
//用于关联OK按钮
public UIButton btnOk;
//用于控制得到输入的文本
public UIInput nameInput;
// Start is called before the first frame update
void Start()
{
//初始化
//一开始初始化length
length = characterPrefabs.Length;
characterGameObjects = new GameObject[length];
for(int i=0;i<length;i++)
{
characterGameObjects[i] = GameObject.Instantiate(characterPrefabs[i], transform.position, transform.rotation) as GameObject;
}
UpdteCharacterShow();
//用于控制点击下一个按钮
btnNext.onClick.Add(new EventDelegate(() =>
{
selectedIndex++;
//判断是否溢出
selectedIndex %= length;
//更新显示
UpdteCharacterShow();
}));
//用于控制上一个按钮的点击
btnLast.onClick.Add(new EventDelegate(() =>
{
selectedIndex--;
//如果还要往前面点击 就放置到最后一个
if (selectedIndex == -1)
selectedIndex = length - 1;
UpdteCharacterShow();
}));
//用于控制OK按钮的点击
btnOk.onClick.Add(new EventDelegate(() =>
{
PlayerPrefs.SetInt("SelectedCharacterIndex", selectedIndex);//存储选择的角色
PlayerPrefs.SetString("name", nameInput.value);//存储输入的名字
//加载下一个场景
SceneManager.LoadScene(3);
}));
}
/// <summary>
/// 用于更新角色的显示
/// </summary>
void UpdteCharacterShow()
{
characterGameObjects[selectedIndex].SetActive(true);
for(int i=0;i<length;i++)
{
if(i!=selectedIndex)
{
characterGameObjects[i].SetActive(false);
}
}
}
}
主要是使用数组将预设体(角色)存储起来进行切换,其中包括一些Unity的操作,有操作不清楚的欢迎私聊问我,我很高兴为您解答!如果这篇笔记对您有所帮助,就点个赞支持一下吧!