赞
踩
【完成本集功能后共享1-10集整套代码】
基于 项目02《游戏-09-开发》Unity3D ,
任务:传送至其他场景,
首先在场景中加入传送门,
设置人物标签,
using UnityEngine;
using UnityEngine.SceneManagement;
using static UIManager;
public class T : MonoBehaviour{
void OnTriggerEnter(Collider other){
// 检查是否与标签为 "Player" 的对象发生碰撞
if (other.CompareTag("Player")){
// 异步加载场景
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene02");
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null){
player.transform.position = new Vector3(13f, 13f, 8f);
player.transform.rotation = Quaternion.Euler(0f, -120f, 0f);
player.transform.localScale = new Vector3(1f, 1f, 1f);
}
UIManager.Instance.OpenPanel(UIConst.MainPanel);
}
}
}
即可实现传送,
放置新传送门,
打开角色预制体,在角色添加子物体Canvas,这样做是让人物传送至其他场景时层级的Canvas可以看到打开的UI,
设置Canvas分辨率,这样设置可以在打包之后同样显示正确的布局,
即完成传送功能,
下面把【项目02《游戏-01-开发》】到【项目02《游戏-10-开发》Unity3D】Unity3D 前10集
的脚本提供如下:
using UnityEngine;
public class CameraCtrl : MonoBehaviour{
public float dis;
public float height;
public float speed;
Transform target;
Vector3 targetPos;
void Start(){
target = MainGame.player.transform;
}
void Update(){
transform.LookAt(target.position + Vector3.up * 1.5f);
targetPos = target.forward * (-dis) + target.up * height + target.position;
}
void LateUpdate(){
transform.position = Vector3.Lerp(transform.position, targetPos, speed);
}
}
using UnityEngine;
public abstract class Living : MonoBehaviour{
public Animator Anim { get; set; }
protected virtual void InitValue() {
Anim = GetComponent<Animator>();
}
protected void Start(){
InitValue();
}
}
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : Living{
float speed = 5;
float rotate;
bool isHoldRotate;//保持旋转角度
void Start(){
base.Start();
SetInput();
contro = GetComponent<CharacterController>();
}
CharacterController contro;
Controls action;
void SetInput(){
action = new Controls();
action.Enable();
action.PlayerCtrl.Move.started += Move;
action.PlayerCtrl.Move.performed += Move;
action.PlayerCtrl.Move.canceled += StopMove;
action.PlayerCtrl.Jump.started += Jump;
action.PlayerCtrl.Rotate.started += Rotate;
action.PlayerCtrl.Rotate.performed += Rotate;
action.PlayerCtrl.HoldRotate.performed += HoldRotate;
action.PlayerCtrl.HoldRotate.canceled += HoldRotate;
action.PlayerAtt.SwordOut.started += SwordOut;
action.PlayerAtt.Att.started += Attack;
}
void Attack(InputAction.CallbackContext obj){
if (Anim.GetCurrentAnimatorStateInfo(0).IsName("Idle_Fight")){
Anim.SetInteger("AttackID", 1);
Anim.SetTrigger("AttackTrigger");
}
else{
int num = Anim.GetInteger("AttackID");
if (num == 6)
return;
if (Anim.GetCurrentAnimatorStateInfo(0).IsName("Attack_" + num))
Anim.SetInteger("AttackID", num + 1);
}
}
void SwordOut(InputAction.CallbackContext obj){
Anim.SetBool("IsSwordOut", !Anim.GetBool("IsSwordOut"));
}
void HoldRotate(InputAction.CallbackContext obj){
if (obj.phase == InputActionPhase.Canceled)
isHoldRotate = false;
else
isHoldRotate = true;
}
void Rotate(InputAction.CallbackContext obj){
rotate = obj.ReadValue<float>();
}
void Jump(InputAction.CallbackContext obj){
Anim.SetTrigger("JumpTrigger");
}
void StopMove(InputAction.CallbackContext obj){
Anim.SetBool("IsRun", false);
}
void Move(InputAction.CallbackContext obj){
Anim.SetBool("IsRun", true);
}
void Ctrl(){
if (Anim.GetCurrentAnimatorStateInfo(0).IsName("Sprint") ||
Anim.GetCurrentAnimatorStateInfo(0).IsName("Run") ||
Anim.GetCurrentAnimatorStateInfo(0).IsName("Idle_ver_A") ||
Anim.GetCurrentAnimatorStateInfo(0).IsName("Idle_Fight")){
float f = action.PlayerCtrl.Move.ReadValue<float>();
contro.Move(transform.forward * f * Time.deltaTime * speed);
contro.Move(transform.up * -9.8f * Time.deltaTime);
if (isHoldRotate)
transform.Rotate(transform.up * rotate * 0.13f);
}
}
void Update(){
Ctrl();
}
}
using System.Collections.Generic;
using UnityEngine;
using static UIManager;
public class MainGame : MonoBehaviour{
public static Player player;
void Awake(){
player = GameObject.Find("Player").GetComponent<Player>();
//背包系统
_instance = this;
DontDestroyOnLoad(gameObject);
}
//背包系统
static MainGame _instance;
PackageTable packageTable;
public static MainGame Instance{
get{
return _instance;
}
}
void Start(){
UIManager.Instance.OpenPanel(UIConst.MainPanel);
}
//对静态数据加载
public PackageTable GetPackageTable(){
if (packageTable == null)
packageTable = Resources.Load<PackageTable>("TableData/PackageTable");
return packageTable;
}
//对动态数据加载
public List<PackageLocalItem> GetPackageLocalData(){
return PackageLocalData.Instance.LoadPackage();
}
//根据ID去表格中拿到指定的数据
public PackageTableItem GetPackageItemById(int id){
List<PackageTableItem> packageDataList = GetPackageTable().dataList;
foreach (PackageTableItem item in packageDataList){
if (item.id == id)
return item;
}
return null;
}
//根据uid去本地数据中拿到动态数据
public PackageLocalItem GetPackageLocalItemByUId(string uid){
List<PackageLocalItem> packageDataList = GetPackageLocalData();
foreach (PackageLocalItem item in packageDataList){
if (item.uid == uid)
return item;
}
return null;
}
public List<PackageLocalItem> GetSortPackageLocalData(){
List<PackageLocalItem> localItems = PackageLocalData.Instance.LoadPackage();
localItems.Sort(new PackageItemComparer());//添加
return localItems;
}
public class PackageItemComparer : IComparer<PackageLocalItem>{
public int Compare(PackageLocalItem a, PackageLocalItem b){
PackageTableItem x = MainGame.Instance.GetPackageItemById(a.id);
PackageTableItem y = MainGame.Instance.GetPackageItemById(b.id);
//首先按star从大到小排序
int starComparison = y.star.CompareTo(x.star);
//如果star相同,则按id从大到小排序
if (starComparison == 0){
int idComparison = y.id.CompareTo(x.id);
if (idComparison == 0)
return b.level.CompareTo(a.level);
return idComparison;
}
return starComparison;
}
}
//添加抽卡阶段字段
public class GameConst {
//武器类型
public const int PackageTypeWeapon = 1;
//食物类型
public const int PackageTypeFood = 2;
}
//添加抽卡阶段
//根据类型获取配置的表格数据
public List<PackageTableItem> GetPackageTableByType(int type){
List<PackageTableItem> packageItems = new List<PackageTableItem>();
foreach (PackageTableItem packageItem in GetPackageTable().dataList){
if (packageItem.type == type)
packageItems.Add(packageItem);
}
return packageItems;
}
//添加抽卡阶段具体逻辑 随机抽卡,获得一件武器
public PackageLocalItem GetLotteryRandom1(){
List<PackageTableItem> packageItems = GetPackageTableByType(GameConst.PackageTypeWeapon);
int index = Random.Range(0, packageItems.Count);
PackageTableItem packageItem = packageItems[index];
PackageLocalItem packageLocalItem = new(){
uid = System.Guid.NewGuid().ToString(),
id = packageItem.id,
num = 1,
level = 1,
isNew = CheckWeaponIsNew(packageItem.id),
};
PackageLocalData.Instance.items.Add(packageLocalItem);
PackageLocalData.Instance.SavePackage();
return packageLocalItem;
}
public bool CheckWeaponIsNew(int id) {
foreach (PackageLocalItem packageLocalItem in GetPackageLocalData()) {
if (packageLocalItem.id == id)
return false;
}
return true;
}
//随机抽卡 十连抽
public List<PackageLocalItem> GetLotteryRandom10(bool sort = false) {
//随机抽卡
List<PackageLocalItem> packageLocalItems = new();
for (int i = 0; i < 10; i++) {
PackageLocalItem packageLocalItem = GetLotteryRandom1();
packageLocalItems.Add(packageLocalItem);
}
//武器排序
if (sort)
packageLocalItems.Sort(new PackageItemComparer());
return packageLocalItems;
}
//添加删除背包道具方法
public void DeletePackageItems(List<string> uids) {
foreach(string uid in uids)
DeletePackageItem(uid,false);
PackageLocalData.Instance.SavePackage();
}
public void DeletePackageItem(string uid, bool needSave = true) {
PackageLocalItem packageLocalItem = GetPackageLocalItemByUId(uid);
if (packageLocalItem == null)
return;
PackageLocalData.Instance.items.Remove(packageLocalItem);
if (needSave)
PackageLocalData.Instance.SavePackage();
}
}
using System.Collections.Generic;
using UnityEngine;
public class UIManager{
static UIManager _instance;
Transform _uiRoot;
//路径配置字典
Dictionary<string, string> pathDict;
//预制体缓存字典
Dictionary<string, GameObject> prefabDict;
//已打开界面的缓存字典
public Dictionary<string, BasePanel> panelDict;
public static UIManager Instance{
get{
if (_instance == null)
_instance = new UIManager();
return _instance;
}
}
public Transform UIRoot{
get{
if (_uiRoot == null){
if (GameObject.Find("Canvas"))
_uiRoot = GameObject.Find("Canvas").transform;
else
_uiRoot = new GameObject("Canvas").transform;
};
return _uiRoot;
}
}
UIManager(){
InitDicts();
}
void InitDicts(){
prefabDict = new Dictionary<string, GameObject>();
panelDict = new Dictionary<string, BasePanel>();
pathDict = new Dictionary<string, string>(){
{ UIConst.PackagePanel,"Package/PackagePanel"},//**
//添加抽卡路径
{ UIConst.LotteryPanel,"Lottery/LotteryPanel"},
//添加主页面转换路径
{ UIConst.MainPanel,"MainPanel"},
};
}
public BasePanel GetPanel(string name){
BasePanel panel = null;
//检查是否已打开
if (panelDict.TryGetValue(name, out panel))
return panel;
return null;
}
public BasePanel OpenPanel(string name){
BasePanel panel = null;
//检查是否已打开
if (panelDict.TryGetValue(name, out panel)){
Debug.Log($"界面已打开 {name}");
return null;
}
//检查路径是否配置
string path = "";
if (!pathDict.TryGetValue(name, out path)){
Debug.Log($"界面名称错误 或未配置路径 {name}");
return null;
}
//使用缓存的预制体
GameObject panelPrefab = null;
if (!prefabDict.TryGetValue(name, out panelPrefab)){
string realPath = "Prefabs/Panel/" + path;
panelPrefab = Resources.Load<GameObject>(realPath) as GameObject;
prefabDict.Add(name, panelPrefab);
}
//打开界面
GameObject panelObject = GameObject.Instantiate(panelPrefab, UIRoot, false);
panel = panelObject.GetComponent<BasePanel>();
panelDict.Add(name, panel);
panel.OpenPanel(name);
return panel;
}
//关闭界面
public bool ClosePanel(string name){
BasePanel panel = null;
if (!panelDict.TryGetValue(name, out panel)){
Debug.LogError($"界面未打开 {name}");
return false;
}
panel.ClosePanel();
return true;
}
public class UIConst{
//配置常量
public const string PackagePanel = "PackagePanel";//**
//添加抽卡阶段
public const string LotteryPanel = "LotteryPanel";
//添加抽卡的主界面阶段
public const string MainPanel = "MainPanel";
}
}
using UnityEngine;
public class BasePanel : MonoBehaviour{
protected bool isRemove = false;
protected new string name;
protected virtual void Awake() { }
public virtual void SetActive(bool active){
gameObject.SetActive(active);
}
public virtual void OpenPanel(string name){
this.name = name;
SetActive(true);
}
public virtual void ClosePanel(){
isRemove = true;
SetActive(false);
Destroy(gameObject);
//移除缓存 表示界面未打开
if (UIManager.Instance.panelDict.ContainsKey(name))
UIManager.Instance.panelDict.Remove(name);
}
}
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using static UIManager;
public class GMCmd{
[MenuItem("CMCmd/读取表格")]
public static void ReadTable(){
PackageTable packageTable = Resources.Load<PackageTable>("TableData/PackageTable");
foreach (PackageTableItem packageItem in packageTable.dataList)
Debug.Log(string.Format($"[id] {packageItem.id} [name] {packageItem.name}"));
}
[MenuItem("CMCmd/创建背包测试数据")]
public static void CreateLocalPackageData(){
//保存数据
PackageLocalData.Instance.items = new List<PackageLocalItem>();
for (int i = 1; i < 9; i++){
PackageLocalItem packageLocalItem = new(){
uid = Guid.NewGuid().ToString(),
id = i,
num = i,
level = i,
isNew = i % 2 == i
};
PackageLocalData.Instance.items.Add(packageLocalItem);
}
PackageLocalData.Instance.SavaPackage();
}
[MenuItem("CMCmd/读取背包测试数据")]
public static void ReadLocalPackageData(){
//读取数据
List<PackageLocalItem> readItems = PackageLocalData.Instance.LoadPackage();
foreach (PackageLocalItem item in readItems)
Debug.Log(item);
}
[MenuItem("CMCmd/打开背包主界面")]
public static void OpenPackagePanel(){
UIManager.Instance.OpenPanel(UIConst.PackagePanel);
}
}
using UnityEngine;
using UnityEngine.UI;
public class LotteryCell : MonoBehaviour{
Transform UIImage;
Transform UIStars;
Transform UINew;
PackageLocalItem packageLocalItem;
PackageTableItem packageTableItem;
LotteryPanel uiParent;
void Awake(){
InitUI();
}
void InitUI(){
UIImage = transform.Find("Center/Image");
UIStars = transform.Find("Bottom/Stars");
UINew = transform.Find("Top/New");
UINew.gameObject.SetActive(false);
}
public void Refresh(PackageLocalItem packageLocalItem, LotteryPanel uiParent) {
//数据初始化
this.packageLocalItem = packageLocalItem;
this.packageTableItem = MainGame.Instance.GetPackageItemById(this.packageLocalItem.id);
this.uiParent = uiParent;
//刷新UI信息
RefreshImage();
}
void RefreshImage() {
Texture2D t = (Texture2D)Resources.Load(this.packageTableItem.imagePath);
Sprite temp = Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0, 0));
UIImage.GetComponent<Image>().sprite = temp;
}
public void RefreshStars() {
for (int i = 0; i < UIStars.childCount; i++) {
Transform star = UIStars.GetChild(i);
if (this.packageTableItem.star > i)
star.gameObject.SetActive(true);
else
star.gameObject.SetActive(false);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LotteryPanel : BasePanel{
Transform UIClose;
Transform UICenter;
Transform UILottery10;
Transform UILottery1;
GameObject LotteryCellPrefab;
protected override void Awake(){
base.Awake();
InitUI();
InitPrefab();
}
void InitUI() {
UIClose = transform.Find("TopRight/Close");
UICenter = transform.Find("Center");
UILottery10 = transform.Find("Bottom/Lottery10");
UILottery1 = transform.Find("Bottom/Lottery1");
UILottery10.GetComponent<Button>().onClick.AddListener(OnLottert10Btn);
UILottery1.GetComponent<Button>().onClick.AddListener(OnLottert1Btn);
UIClose.GetComponent<Button>().onClick.AddListener (OnClose);
}
void OnClose(){
print(">>>>>>>> OnClose");
ClosePanel();
UIManager.Instance.OpenPanel(UIManager.UIConst.MainPanel);
}
void OnLottert1Btn(){
print(">>>>>>>> OnLottert1Btn");
//销毁原本的卡片
for (int i = 0; i < UICenter.childCount; i++)
Destroy(UICenter.GetChild(i).gameObject);
//抽卡获得一张新的物品
PackageLocalItem item = MainGame.Instance.GetLotteryRandom1();
Transform LotteryCellTran = Instantiate(LotteryCellPrefab.transform, UICenter) as Transform;
// 对卡片做信息展示刷新
LotteryCell lotteryCell = LotteryCellTran.GetComponent<LotteryCell>();
lotteryCell.Refresh(item, this);
}
void OnLottert10Btn(){
print(">>>>>>>> OnLottert10Btn");
List<PackageLocalItem> packageLocalItems = MainGame.Instance.GetLotteryRandom10(sort: true);
for (int i = 0; i < UICenter.childCount; i++)
Destroy(UICenter.GetChild(i).gameObject);
foreach (PackageLocalItem item in packageLocalItems){
Transform LotteryCellTran = Instantiate(LotteryCellPrefab.transform, UICenter) as Transform;
// 对卡片做信息展示刷新
LotteryCell lotteryCell = LotteryCellTran.GetComponent<LotteryCell>();
lotteryCell.Refresh(item, this);
}
}
void InitPrefab() {
LotteryCellPrefab = Resources.Load("Prefabs/Panel/Lottery/LotteryItem") as GameObject;
}
}
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class MainPanel : BasePanel{
Transform UILottery;
Transform UIPackage;
Transform UIQuitBtn;
protected override void Awake(){
base.Awake();
InitUI();
}
void InitUI(){
UILottery = transform.Find("Top/LotteryBtn");
UIPackage = transform.Find("Top/PackageBtn");
UIQuitBtn = transform.Find("BottomLeft/QuitBtn");
UILottery.GetComponent<Button>().onClick.AddListener(OnBtnLottery);
UIPackage.GetComponent<Button>().onClick.AddListener(OnBtnPackage);
UIQuitBtn.GetComponent<Button>().onClick.AddListener(OnQuitGame);
}
void OnQuitGame(){
print(">>>>> OnQuitGame");
//EditorApplication.isPlaying = false;
Application.Quit();
}
void OnBtnPackage(){
print(">>>>> OnBtnPackage");
UIManager.Instance.OpenPanel(UIManager.UIConst.PackagePanel);
ClosePanel();
}
void OnBtnLottery(){
print(">>>>> OnBtnLottery");
UIManager.Instance.OpenPanel(UIManager.UIConst.LotteryPanel);
ClosePanel();
}
}
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PackageCell : MonoBehaviour,IPointerClickHandler,IPointerEnterHandler,IPointerExitHandler{
Transform UIIcon;
Transform UIHead;
Transform UINew;
Transform UISelect;
Transform UILevel;
Transform UIStars;
Transform UIDeleteSelect;
//添加
Transform UISelectAni;
Transform UIMouseOverAni;
//动态数据
PackageLocalItem packageLocalData;
//静态数据
PackageTableItem packageTableItem;
//父物体也就是PackagePanel本身
PackagePanel uiParent;
void Awake(){
InitUIName();
}
void InitUIName(){
UIIcon = transform.Find("Top/Icon");
UIHead = transform.Find("Top/Head");
UINew = transform.Find("Top/New");
UILevel = transform.Find("Bottom/LevelText");
UIStars = transform.Find("Bottom/Stars");
UISelect = transform.Find("Select");
UIDeleteSelect = transform.Find("DeleteSelect");
//添加
UIMouseOverAni = transform.Find("MouseOverAni");
UISelectAni = transform.Find("SelectAni");
UIDeleteSelect.gameObject.SetActive(false);
//添加
UIMouseOverAni.gameObject.SetActive(false);
UISelectAni.gameObject.SetActive(false);
}
//刷新
public void Refresh(PackageLocalItem packageLocalData, PackagePanel uiParent){
//数据初始化
this.packageLocalData = packageLocalData;
this.packageTableItem = MainGame.Instance.GetPackageItemById(packageLocalData.id);
this.uiParent = uiParent;
//等级信息
UILevel.GetComponent<Text>().text = "Lv." + this.packageLocalData.level.ToString();
//是否是新获得?
UINew.gameObject.SetActive(this.packageLocalData.isNew);
Debug.Log("ImagePath: " + this.packageTableItem.imagePath);
//物品的图片
Texture2D t = (Texture2D)Resources.Load(this.packageTableItem.imagePath);
if (t != null){
Sprite temp = Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0, 0));
// 继续处理 Sprite 对象
UIIcon.GetComponent<Image>().sprite = temp;
}
else{
// 处理纹理加载失败的情况
Debug.LogError("Failed to load texture.");
}
//刷新星级
RefreshStars();
}
//刷新星级
public void RefreshStars(){
for (int i = 0; i < UIStars.childCount; i++){
Transform star = UIStars.GetChild(i);
if (this.packageTableItem.star > i)
star.gameObject.SetActive(true);
else
star.gameObject.SetActive(false);
}
}
public void OnPointerClick(PointerEventData eventData){
//if (this.uiParent.ChooseUid == this.packageLocalData.uid)
// return;
//根据点击设置最新的uid 进而刷新详情界面
//this.uiParent.ChooseUid = this.packageLocalData.uid;
//UISelectAni.gameObject.SetActive(true);
//UISelectAni.GetComponent<Animator>().SetTrigger("In");
//添加删除方法:
if(this.uiParent.curMode == PackageMode.delete)
this.uiParent.AddChooseDeleteUid(this.packageLocalData.uid);
if (this.uiParent.ChooseUid == this.packageLocalData.uid)
return;
//根据点击设置最新的uid -> 进而刷新详情界面
this.uiParent.ChooseUid = this.packageLocalData.uid;
UISelectAni.gameObject.SetActive(true);
UISelectAni.GetComponent<Animator>().SetTrigger("In");
}
public void OnPointerEnter(PointerEventData eventData){
UIMouseOverAni.gameObject.SetActive(true);
UIMouseOverAni.GetComponent<Animator>().SetTrigger("In");
}
public void OnPointerExit(PointerEventData eventData){
Debug.Log($"OnPointerExit {eventData.ToString()}");
}
//添加删除方法
public void RefershDeleteState() {
if (this.uiParent.deleteChooseUid.Contains(this.packageLocalData.uid))
this.UIDeleteSelect.gameObject.SetActive(true);
else
this.UIDeleteSelect.gameObject.SetActive(false);
}
}
using UnityEngine;
using UnityEngine.UI;
public class PackageDetail : MonoBehaviour{
Transform UIStars;
Transform UIDescription;
Transform UIIcon;
Transform UITitle;
Transform UILevelText;
Transform UISkillDescription;
PackageLocalItem packageLocalData;
PackageTableItem packageTableItem;
PackagePanel uiParent;
void Awake(){
InitUIName();
Test();
}
void Test() {
Refresh(MainGame.Instance.GetPackageLocalData()[7], null);
}
void InitUIName(){
UIStars = transform.Find("Center/Stars");
UIDescription = transform.Find("Center/Description");
UIIcon = transform.Find("Center/Icon");
UITitle = transform.Find("Top/Title");
UILevelText = transform.Find("Bottom/LevelPnl/LevelText");
UISkillDescription = transform.Find("Bottom/Description");
}
public void Refresh(PackageLocalItem packageLocalData, PackagePanel uiParent) {
//初始化:动态数据,静态数据,父物品逻辑
this.packageLocalData = packageLocalData;
this.packageTableItem = MainGame.Instance.GetPackageItemById(packageLocalData.id);
this.uiParent = uiParent;
//等级
UILevelText.GetComponent<Text>().text = string.Format($"Lv.{this.packageLocalData.level.ToString()}");
//简短描述
UIDescription.GetComponent<Text>().text = this.packageTableItem.description;
//详细描述
UISkillDescription.GetComponent<Text>().text = this.packageTableItem.skillDescription;
//物品名称
UITitle.GetComponent<Text>().name = this.packageTableItem.name;
//图片加载
Texture2D t = (Texture2D)Resources.Load(this.packageTableItem.imagePath);
Sprite temp = Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0, 0));
UIIcon.GetComponent<Image>().sprite = temp;
//星级处理
RefreshStars();
}
public void RefreshStars(){
for (int i = 0; i < UIStars.childCount; i++) {
Transform star = UIStars.GetChild(i);
if(this.packageTableItem.star > i)
star.gameObject.SetActive(true);
else
star.gameObject.SetActive(false);
}
}
}
using System.Collections.Generic;
using UnityEngine;
public class PackageLocalData{
static PackageLocalData _instance;
public static PackageLocalData Instance{
get{
if (_instance == null)
_instance = new PackageLocalData();
return _instance;
}
}
//存
public List<PackageLocalItem> items;
public void SavaPackage(){
string inventoryJson = JsonUtility.ToJson(this);
PlayerPrefs.SetString("PackageLocalData", inventoryJson);
PlayerPrefs.Save();
}
//取
public List<PackageLocalItem> LoadPackage(){
if (items != null)
return items;
if (PlayerPrefs.HasKey("PackageLocalData")){
string inventoryJson = PlayerPrefs.GetString("PackageLocalData");
PackageLocalData packageLocalData = JsonUtility.FromJson<PackageLocalData>(inventoryJson);
items = packageLocalData.items;
return items;
}
else{
items = new List<PackageLocalItem>();
return items;
}
}
//添加抽卡阶段
public void SavePackage(){
string inventoryJson = JsonUtility.ToJson(this);
PlayerPrefs.SetString("PackageLocalData", inventoryJson);
PlayerPrefs.Save();
}
}
[System.Serializable]
public class PackageLocalItem{
public string uid;
public int id;
public int num;
public int level;
public bool isNew;
public override string ToString(){
return string.Format($"[id] {id} [num] {num}");
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum PackageMode{
normal,
delete,
sort,
}
public class PackagePanel : BasePanel{
Transform UIMenu;
Transform UIMenuWeapon;
Transform UIMenuFood;
Transform UITabName;
Transform UICloseBtn;
Transform UICenter;
Transform UIScrollView;
Transform UIDetailPanel;
Transform UILeftBtn;
Transform UIRightBtn;
Transform UIDeletePanel;
Transform UIDeleteBackBtn;
Transform UIDeleteInfoText;
Transform UIDeleteConfirmBtn;
Transform UIBottomMenus;
Transform UIDeleteBtn;
Transform UIDetailBtn;
//添加
public GameObject PackageUIItemPrefab;
//添加一列用来容纳所有被选中的物品uid
public List<string> deleteChooseUid;
//添加删除属性
public PackageMode curMode = PackageMode.normal;
public void AddChooseDeleteUid(string uid) {
this.deleteChooseUid ??= new List<string>();
if(!this.deleteChooseUid.Contains(uid))
this.deleteChooseUid.Add(uid);
else
this.deleteChooseUid.Remove(uid);
RefreshDeletePanel();
}
//添加删除选中项
void RefreshDeletePanel(){
RectTransform scrollContent = UIScrollView.GetComponent<ScrollRect>().content;
foreach(Transform cell in scrollContent){
PackageCell packageCell = cell.GetComponent<PackageCell>();
//todo: 物品刷新选中状态
packageCell.RefershDeleteState();
}
}
//添加 表示当前选中的物品时哪一个uid
string _chooseUid;
public string ChooseUid {
get { return _chooseUid; }
set {
_chooseUid = value;
RefreshDetail();
}
}
void RefreshDetail() {
//找到uid对应的动态数据
PackageLocalItem localItem = MainGame.Instance.GetPackageLocalItemByUId(ChooseUid);
//刷新详情界面
UIDetailPanel.GetComponent<PackageDetail>().Refresh(localItem, this);
}
override protected void Awake(){
base.Awake();
InitUI();
}
//添加1
void Start(){
RefreshUI();
}
//添加1
void RefreshUI(){
RefreshScroll();
}
//添加1
void RefreshScroll(){
//清理滚动容器中原本的物品
RectTransform scrollContent = UIScrollView.GetComponent<ScrollRect>().content;
for (int i = 0; i < scrollContent.childCount; i++)
Destroy(scrollContent.GetChild(i).gameObject);
//获取本地数据的方法拿到自己身上背包数据 并且根据背包数据初始化滚动容器
foreach (PackageLocalItem localData in MainGame.Instance.GetSortPackageLocalData()){
Transform PackageUIItem = Instantiate(PackageUIItemPrefab.transform, scrollContent) as Transform;
PackageCell packageCell = PackageUIItem.GetComponent<PackageCell>();
//添加2
packageCell.Refresh(localData, this);
}
}
void InitUI(){
InitUIName();
InitClick();
}
void InitUIName(){
UIMenu = transform.Find("TopCenter/Menu");
UIMenuWeapon = transform.Find("TopCenter/Menus/Weapon");
UIMenuFood = transform.Find("TopCenter/Menus/Food");
UITabName = transform.Find("LeftTop/TabName");
UICloseBtn = transform.Find("RightTop/Close");
UICenter = transform.Find("Center");
UIScrollView = transform.Find("Center/Scroll View");
UIDetailPanel = transform.Find("Center/DetailPanel");
UILeftBtn = transform.Find("Left/Button");
UIRightBtn = transform.Find("Right/Button");
UIDeletePanel = transform.Find("Bottom/DeletePanel");
UIDeleteBackBtn = transform.Find("Bottom/DeletePanel/Back");
UIDeleteInfoText = transform.Find("Bottom/DeletePanel/InfoText");
UIDeleteConfirmBtn = transform.Find("Bottom/DeletePanel/ConfirmBtn");
UIBottomMenus = transform.Find("Bottom/BottomMenus");
UIDeleteBtn = transform.Find("Bottom/BottomMenus/DeleteBtn");
UIDetailBtn = transform.Find("Bottom/BottomMenus/DetailBtn");
UIDeletePanel.gameObject.SetActive(false);
UIBottomMenus.gameObject.SetActive(true);
}
void InitClick(){
UIMenuWeapon.GetComponent<Button>().onClick.AddListener(OnClickWeapon);
UIMenuFood.GetComponent<Button>().onClick.AddListener(OnClickFood);
UICloseBtn.GetComponent<Button>().onClick.AddListener(OnClickClose);
UILeftBtn.GetComponent<Button>().onClick.AddListener(OnClickLeft);
UIRightBtn.GetComponent<Button>().onClick.AddListener(OnClickRight);
UIDeleteBackBtn.GetComponent<Button>().onClick.AddListener(OnDeleteBack);
UIDeleteConfirmBtn.GetComponent<Button>().onClick.AddListener(OnDeleteConfirm);
UIDeleteBtn.GetComponent<Button>().onClick.AddListener(OnDelete);
UIDetailBtn.GetComponent<Button>().onClick.AddListener(OnDetail);
}
void OnDetail(){
print(">>>>>>> OnDetail()");
}
//进入删除模式 ; 左下角删除按钮
void OnDelete(){
print(">>>>>>> OnDelete()");
curMode = PackageMode.delete;
UIDeletePanel.gameObject.SetActive(true);
}
//确认删除
void OnDeleteConfirm(){
print(">>>>>>> OnDeleteConfirm()");
if (this.deleteChooseUid == null)
return;
if (this.deleteChooseUid.Count == 0)
return;
MainGame.Instance.DeletePackageItems(this.deleteChooseUid);
//删除完成后刷新整个背包页面
RefreshUI();
}
//退出删除模式
void OnDeleteBack(){
print(">>>>>>> OnDeleteBack()");
curMode = PackageMode.normal;
UIDeletePanel.gameObject.SetActive(false);
//重置选中的删除列表
deleteChooseUid = new List<string>();
//刷新选中状态
RefreshDeletePanel();
}
void OnClickRight(){
print(">>>>>>> OnClickRight()");
}
void OnClickLeft(){
print(">>>>>>> OnClickLeft()");
}
void OnClickWeapon(){
print(">>>>>>> OnClickWeapon()");
}
void OnClickFood(){
print(">>>>>>> OnClickFood()");
}
void OnClickClose(){
ClosePanel();
UIManager.Instance.OpenPanel(UIManager.UIConst.MainPanel);
}
}
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Water/PackageTable", fileName = "PackageTable")]
public class PackageTable : ScriptableObject{
public List<PackageTableItem> dataList = new List<PackageTableItem>();
}
[System.Serializable]
public class PackageTableItem{
public int id;
public int type;
public int star;
public string name;
public string description;
public string skillDescription;
public string imagePath;
}
using UnityEngine;
using UnityEngine.SceneManagement;
using static UIManager;
public class T : MonoBehaviour{
void OnTriggerEnter(Collider other){
// 检查是否与标签为 "Player" 的对象发生碰撞
if (other.CompareTag("Player")){
// 异步加载场景
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene02");
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null){
player.transform.position = new Vector3(13f, 13f, 8f);
player.transform.rotation = Quaternion.Euler(0f, -120f, 0f);
player.transform.localScale = new Vector3(1f, 1f, 1f);
}
UIManager.Instance.OpenPanel(UIConst.MainPanel);
}
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class TBack : MonoBehaviour{
void OnTriggerEnter(Collider other){
// 检查是否与标签为 "Player" 的对象发生碰撞
if (other.CompareTag("Player")){
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null){
// 将玩家物理状态重置为默认值
Rigidbody playerRigidbody = player.GetComponent<Rigidbody>();
if (playerRigidbody != null){
playerRigidbody.velocity = Vector3.zero;
playerRigidbody.angularVelocity = Vector3.zero;
playerRigidbody.isKinematic = false;
}
// 异步加载场景
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene04");
// 设置加载完成后的回调
asyncLoad.completed += (op) =>{
// 在加载完成后重新定位 Player 位置、旋转和尺寸
player.transform.position = new Vector3(100f, 10f, 120f);
player.transform.rotation = Quaternion.Euler(0f, 180f, 0f);
player.transform.localScale = new Vector3(1f, 1f, 1f);
};
}
}
}
}
End.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。