//使用持久化存储保存更换武器的案例
//case_PlayerPrefs_ChangeWeapons.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class case_PlayerPrefs_ChangeWeapons : MonoBehaviour
{
//案例-换武器
//定义所有武器obj的数组
public GameObject[] weaponsAllOBJ;
//定义当前武器obj的变量
private GameObject weaponsOBJ;
//定义存储随机数的变量
private int randomNum;
private void Start()
{
//Resources.LoadAll 获取资源目录下的所有对应数据类型的资源,并返回数组
weaponsAllOBJ = Resources.LoadAll<GameObject>("MonsterBaseTeam/3D/weapons/");
print("资源里面的武器物体有: " + weaponsAllOBJ.Length);
//游戏开始时判定持久化存储是否存有武器的索引号,有则生成之前的武器
if (PlayerPrefs.HasKey("weapons"))
{
weaponsOBJ = Instantiate(weaponsAllOBJ[PlayerPrefs.GetInt("weapons")], this.transform.position, this.transform.rotation, this.transform);
}
}
private void OnGUI()
{
if (GUILayout.Button("随机更换装备"))
{
//判断下当前武器变量是否存在物体,是,则销毁在创建新的武器
if (weaponsOBJ != null)
{
GameObject.Destroy(weaponsOBJ);
}
//随机数组索引生成武器游戏物体
randomNum = Random.Range(0, weaponsAllOBJ.Length);
//武器数组索引根据随机数生成武器,生成在父物体下
weaponsOBJ = Instantiate(weaponsAllOBJ[randomNum], this.transform.position, this.transform.rotation,this.transform);
}
if (GUILayout.Button("保存装备"))
{
//保存武器的索引号
PlayerPrefs.SetInt("weapons", randomNum);
}
if (GUILayout.Button("清除装备"))
{
//判断下当前武器变量是否存在物体,是,则销毁在创建新的武器
if (weaponsOBJ != null)
{
GameObject.Destroy(weaponsOBJ);
}
if (PlayerPrefs.HasKey("weapons"))
{
PlayerPrefs.DeleteKey("weapons");
}
}
}
}
|