创建一个工具类,控制游戏中UI面板显示

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Consts  {  
}
public enum PanelType  //枚举类型,目前只有一个 游戏开始的UI面板
{
    StartPanel
}

注意:① 数据类不需要继承自MonoBehaviour,它不需要挂在游戏物体身上 

           ② StartPanel 游戏开始UI面板做好后,拖到Resources文件夹下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class Tool{

    static Transform uiParent; //父物体

    public static Transform UiParent
    {
        get
        {
            if (uiParent == null)
                uiParent = GameObject.Find("Canvas").transform;//如果父物体为空,把Canavs作为父物体
            return uiParent;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="panelType 面板类型"></param>
    /// <returns></returns>
    public static GameObject CreateUIPanel(PanelType panelType)
    {
        GameObject go = Resources.Load<GameObject>(panelType.ToString()); 
        if(go == null)
        {
            Debug.Log(panelType.ToString() + "不存在。");
            return null;
        }
        else
        {
            GameObject currentPanel = GameObject.Instantiate(go);
            currentPanel.name = panelType.ToString();
            currentPanel.transform.SetParent(UiParent,false); //设置成父物体,UI不需要是世界坐标
            return go;
        }
    }
}

注意:① 工具类不需要挂在游戏物体身上

           ② 加载UI面板,利用Resources.Load()方法 ,其路径只需要把 CreateUIPanel里 枚举类型的参数转化成String类型

           ③ 要看到UI面板,还需要实例化加载的资源

           ④ 实例化加载的UI面板要设置其父物体为Canvas

           ⑤ 设置UI面板父物体时,不需要是世界坐标,否则UI面板 的显示会受父物体影响(旋转度等等)

易错: ① currentPanel.transform.SetParent(UiParent,false);   注意:UiParent 而不是uiParent

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值