项目02《游戏-10-开发》Unity3D

【完成本集功能后共享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.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2774124.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

Canvas的js库:Konva.js-像操作DOM一样,操作canvas

hello&#xff0c;我是贝格前端工场&#xff0c;最近在学习canvas&#xff0c;分享一些canvas的一些知识点笔记&#xff0c;本期分享Konva.js这个canvas框架&#xff0c;欢迎老铁们一同学习&#xff0c;欢迎关注&#xff0c;如有前端项目可以私信贝格。 Konva.js是一个强大的HT…

WordPress突然后台无法管理问题

登录WordPress后台管理评论&#xff0c;发现点击编辑、回复均无反应。 尝试清除缓存、关闭CF连接均无效。 查看插件时发现关闭wp-china-yes插件可以解决问题。 后来又测试了下发现加速管理后台这项&#xff0c;在启用时会发生点击无效问题&#xff0c;禁用就好了&#xff0c;不…

蓝桥杯Web应用开发-CSS3 新特性【练习二:获得焦点验证】

页面上有一个姓名输入框和一个密码输入框&#xff0c;当聚焦输入框时&#xff0c;输入框的背景颜色会发生改变&#xff0c; 新建一个 index3.html 文件&#xff0c;在其中写入以下内容。 <!DOCTYPE html> <html lang"en"><head><meta charset&…

FlinkSql 窗口函数

Windowing TVF 以前用的是Grouped Window Functions&#xff08;分组窗口函数&#xff09;&#xff0c;但是分组窗口函数只支持窗口聚合 现在FlinkSql统一都是用的是Windowing TVFs&#xff08;窗口表值函数&#xff09;&#xff0c;Windowing TVFs更符合 SQL 标准且更加强大…

如何在Mac上允许主流浏览器使用弹出式窗口?这里有详细步骤

这篇文章教你如何关闭流行的Mac浏览器上的弹出窗口阻止程序,包括Safari、Chrome和Firefox。它还探讨了你可能希望这样做的原因及其影响。 如何在Mac上允许Safari使用弹出窗口 如果你经常在Mac上使用Safari,你会注意到默认情况下弹出窗口阻止程序是打开的。有时,这并不方便…

创建一个VUE项目(vue2和vue3)

背景&#xff1a;电脑已经安装完vue2和vue3环境 一台Mac同时安装vue2和vue3 https://blog.csdn.net/c103363/article/details/136059783 创建vue2项目 vue init webpack "项目名称"创建vue3项目 vue create "项目名称"

Page 260~264 11.3.2 wxWidgets GUI项目例子

打开&#xff0c;wx28_guiMain.h 30,31,32分别是关闭&#xff0c;退出&#xff0c;和“关于”事件&#xff0c;分别对应着关闭&#xff0c;退出和About三个菜单的出发时间 我们在35,27行分别写OnMotion和OnPaint两个函数&#xff0c;入参都是鼠标事件&#xff0c;分别对应着鼠…

深度学习(14)--x.view()详解

在torch中&#xff0c;常用view()函数来改变tensor的形状 查询官方文档&#xff1a; torch.Tensor.view — PyTorch 2.2 documentationhttps://pytorch.org/docs/stable/generated/torch.Tensor.view.html#torch.Tensor.view示例 1.创建一个4x4的二维数组进行测试 x torch.…

数字图像处理(实践篇)四十七 OpenCV-Python 高动态范围HDR

目录 一 HDR 二 实践 高质量的图像具备的要素如下: ①分辨率 图像中的像素数量。在特定屏幕尺寸下,分辨率越高,像素越多,显示的细节更精细。 ②位深度

[VulnHub靶机渗透] dpwwn: 1

&#x1f36c; 博主介绍&#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【应急响应】 【python】 【VulnHub靶场复现】【面试分析】 &#x1f389;点赞➕评论➕收藏…

【Linux系统学习】3.Linux用户和权限

Linux用户和权限 1.认知root用户 1.1 root用户&#xff08;超级管理员&#xff09; 无论是Windows、MacOS、Linux均采用多用户的管理模式进行权限管理。 在Linux系统中&#xff0c;拥有最大权限的账户名为&#xff1a;root&#xff08;超级管理员&#xff09; 而在前期&#…

2/7 算法每日N题(二分+双指针)

第一题&#xff1a; class Solution { public:int search(vector<int>& nums, int target) {int left 0, right nums.size() - 1;while(left < right){int mid (right - left) / 2 left;int num nums[mid];if (num target) {return mid;} else if (num >…

【知识整理】管理即服务,识人、识己

1. 背景 一个人的力量是有限的&#xff0c;如何规模化生产&#xff0c;人员的规模化组织&#xff0c;如何提升合作的规模和效率。 管理的本质&#xff1a; 1、服务他人&#xff1f; 2、激发主动性&#xff1f; 3、氛围宽松&#xff1f; 上面是理念&#xff0c; 1、那如何…

BUGKU-WEB 留言板

题目描述 题目无需登录后台&#xff01;需要xss平台接收flag&#xff0c; http协议需要http协议的xss平台打开场景后界面如下&#xff1a; 解题思路 看到此类的题目&#xff0c;应该和存储型xss有关&#xff0c;也就是将恶意代码保存到服务器端即然在服务器端&#xff0c;那就…

基于全连接神经网络模型的手写数字识别

基于全连接神经网络模型的手写数字识别 一. 前言二. 设计目的及任务描述2.1 设计目的2.2 设计任务 三. 神经网络模型3.1 全连接神经网络模型方案3.2 全连接神经网络模型训练过程3.3 全连接神经网络模型测试 四. 程序设计 一. 前言 手写数字识别要求利用MNIST数据集里的70000张…

17:定时器编程实战

1、实验目的 (1)使用定时器来完成LED闪烁 (2)原来实现闪烁时中间的延迟是用delay函数实现的&#xff0c;在delay的过程中CPU要一直耗在这里不能去做别的事情。这是之前的缺点 (3)本节用定时器来定一个时间&#xff08;譬如0.3s&#xff09;&#xff0c;在这个定时器定时时间内…

STM32F1 - 启动文件startup_stm32f10x_hd.s

startup_stm32f10x_hd.s 1> 启动文件类型2> 启动文件干了点啥&#xff1f; 1> 启动文件类型 表格来自stm32f10x.h总结&#xff0c;省略STM32 value line devices系列产品 2> 启动文件干了点啥&#xff1f;

多项式回归与模型泛化

多项式回归 生成数据 import numpy as np import matplotlib.pyplot as plt x np.random.uniform(-3, 3, size100) X x.reshape(-1, 1) y 0.5 * x**2 x 2 np.random.normal(0, 1, 100) plt.scatter(x, y) plt.show()线性回归拟合数据集 from sklearn.linear_model imp…

如何判断线程池已经执行完所有任务了?

目录 不判断的问题 方法1&#xff1a;isTerminated 缺点分析 扩展&#xff1a;线程池的所有状态 方法2&#xff1a;getCompletedTaskCount 方法说明 优缺点分析 方法3&#xff1a;CountDownLatch&#xff08;推荐&#xff09; 优缺点分析 方法4&#xff1a;CyclicBar…

VS Code中主程序C文件引用了另一个.h头文件,编译时报错找不到函数

目录 一、问题描述二、问题原因三、解决方法四、扩展五、通过CMake进行配置 一、问题描述 VS Code中主程序C文件引用了另一个.h头文件&#xff0c;编译时报错找不到函数 主程序 main.c #include <stdio.h> #include "sumaa.h"int main(int, char**){printf(&q…