精华内容
下载资源
问答
  • Unity3D中的网络 一、WWW 1-1 Get 1-2 Post 1-3 案例(网络下载,本地存储与读取) 二、UnityWebRequest 2-1 Get 2-2 Post 2-3 案例(Json解析,展示) 2-4 斗鱼API请求实战(Get) 2-5 项目API请求实战(Post) ...

    正所谓:没有网络是没有灵魂的

    • 欢迎关注公众号:雷潮课堂
      公众号二维码.jpg

    Unity3D中的网络

    一、WWW

    1-1 Get
    1-2 Post
    1-3 案例(网络下载,本地存储与读取)

    二、UnityWebRequest

    2-1 Get
    2-2 Post
    2-3 案例(Json解析,展示)
    2-4 斗鱼API请求实战(Get)
    2-5 项目API请求实战(Post)

    三、HttpWebRequest

    3-1 代码演示

    一、WWW

    Unity中的WWW(Unity2017以后已标记为弃用状态,但是仍然可以用它来入门)
    WWW用于下载资源和打开Web网站,包含:Get/Post请求,本地资源文件下载,服务器资源下载。关于使用www方式加载AssetBundle资源,可以关注文章AssetBundle使用

    1-1.Get

    1.一个链接中,参数是包括在链接中的,链接中的?后面都是参数;
    2.服务器不会自动分配空间,传输的内容会比较小。

        string urlPath = "http://www.....";//资源网络路径
        string file_SaveUrl = @"D:\test.rar";//资源保路径
        FileInfo file; 
        void Start ()
        {
            file = new FileInfo(file_SaveUrl);
            Debug.Log(file_SaveUrl);
            StartCoroutine(DownFile(urlPath));
        }
    
       
        /// <summary>
        /// 下载文件
        /// </summary>
        IEnumerator DownFile(string url)
        {
            WWW www = new WWW(url);
            yield return www;
            if (www.isDone)
            {
                Debug.Log("下载完成");
                byte[] bytes = www.bytes;
                CreatFile(bytes);
            }
        }
    
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="bytes"></param>
        void CreatFile(byte[] bytes)
        {
            Stream stream;
            stream = file.Create();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
            stream.Dispose();
    }
    
    1-2.Post

    1.参数在表单里面。
    2.服务器在底层检测到是Post请求,则会自动分配一个大的空间
    3.例如声音,压缩包,视频等比较大的数据

    • WWW的使用
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class LoginWWW : MonoBehaviour {
    
        string url;
        public Image img;
        //public InputField put;
    	void Start () {
            url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540877217182&di=9d56ef557a007c78b543278db41cbb28&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fd6ca7bcb0a46f21fd757a52ffb246b600c33ae6f.jpg";
            // Get
            StartCoroutine(GetLoadBg(url));
    
            // Post  请求头,请求体
            //Dictionary<string, string> dic = new Dictionary<string, string>();
            //dic.Add("uEmail", "136087399@qq.com");
            //dic.Add("uPwd", "1314521");
            //StartCoroutine(PostLoadLogin(url,dic));
        }
    
        // Get
        IEnumerator GetLoadBg(string url)
        {
            WWW w = new WWW(url);
            yield return w;
            // 返回字节数的长度
            //Debug.Log(w.size);
            // 打印响应头
            //foreach (var item in w.responseHeaders)
            //{
            //    Debug.Log(item);
            //}
            //  错误为空 ||下载完毕 || 图片下载完毕
            if (w.error == null || w.isDone == true || w.progress == 1)
            {
                img.sprite = Sprite.Create(w.texture, new Rect(0, 0, Screen.width, Screen.height), new Vector2(0.5f, 0.5f));
            }
            else
            {
                Debug.Log(w.error);
            }
        }
    
        // Post
        IEnumerator PostLoadLogin(string url, Dictionary<string, string> dic)
        {
            WWWForm f = new WWWForm();
            foreach (KeyValuePair<string,string> item in dic)
            {
                f.AddField(item.Key, item.Value);
            }
            WWW w = new WWW(url,f);
            yield return w;
            if (w.isDone)
            {
                if (w.error == null)
                {
                    Debug.Log("加载成功");
                }
                else
                {
                    Debug.Log(w.error);
                }
            }
            else
            {
                Debug.Log("正在下载");
            }
        }
    }
    
    1-3.案例
    • 网络下载文件,增加本地读取
        string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594893269883&di=8acc2ec9ae60c906032b15feafe988ee&imgtype=0&src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2Fd42ccebee956f1c275d33f12179d804a22590e92.jpg";
        public RawImage raw;
        int index = 0;
      
        private void OnGUI()
        {
            if (GUILayout.Button("网络加载图片"))
            {
                index++;
                StartCoroutine(LoadImage(url));
            }
            if (GUILayout.Button("本地加载图片"))
            {
                string path = PlayerPrefs.GetString("url");
                StartCoroutine(LoadImage(path));
            }
        }
       // 加载(网络路径/本地路径)
        IEnumerator LoadImage(string url)
        {
            WWW w = new WWW(url);
            yield return w;
            if (w.isDone || w.error == null || w.progress == 1)
            {
                raw.texture = w.texture;
                // 保存在本地(文件路径)
                SaveImage(w.texture);
            }
        }
        // 存储图片
        public void SaveImage(Texture2D png)
        {
            byte[] dataBytes = png.EncodeToPNG();    
             //  Application.dataPath = 文件夹Assets的路径,一般是保存在 Application.streamingAssetsPath路径下
            string strSaveFile = Application.dataPath  + @"\Image\" + index + "_"  + ".jpg";  
            File.WriteAllBytes(strSaveFile, dataBytes);
            // 数据持久化 (通过一个URl,保存一个文件路径)
            PlayerPrefs.SetString("url", strSaveFile);
        }
    

    二、UnityWebRequest

    上面我们讲过WWW方式,5.2版本后,Unity采用了UnityWebRequest 类,利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交。
    UnityWebRequest 由三个元素组成。
    ◾UploadHandler 处理数据 将数据发送到服务器 的对象
    ◾DownloadHandler 从服务器接收数据 的对象
    ◾UnityWebRequest 负责 HTTP 通信流量控制来管理上面两个对象的对象。

    2-1.GET
    public class LoginWebRequist : MonoBehaviour {
        string url;
        public RawImage img;
    	void Start () {
    		url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540877217182&di=9d56ef557a007c78b543278db41cbb28&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fd6ca7bcb0a46f21fd757a52ffb246b600c33ae6f.jpg";
            StartCoroutine(LoadImage(url));
        }
        IEnumerator LoadImage(string url)
        {   
            UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
            // DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
            yield return www.SendWebRequest();
            Debug.Log(www.downloadHandler.data.Length);
            if (www.isHttpError)
            {
    
            }
            else
            {
                if (www.responseCode == 200)
                {
                    Debug.Log("连接成功");
                    //byte[] result = www.downloadHandler.data;
                    //int width = 0, height = 0;
                    //Texture2D t = new Texture2D(width,height);
                    //t.LoadImage(result);
                    //img.texture = t;
                    img.texture = DownloadHandlerTexture.GetContent(www);
                }
                else {
                    Debug.Log("连接不成功");
                    // 请检查网络,或者重新刷新
                }       
            }
        }
    }
    
    2-2.POST
     void Start() {  
            StartCoroutine( PostUrl(url, postData));        
        }  
    public IEnumerator PostUrl(string url, string postData)
        {
            using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
            {
                // 上传请求头,byte[]数组
                byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
                www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
                www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
               //  请求头可以不写
               // www.SetRequestHeader("Content-Type", "application/json");
                yield return www.Send();
                if (www.isError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    // Show results as text  
                    if (www.responseCode == 200)
                    {
                        Debug.Log(www.downloadHandler.text);
                    }
                }
            }
        }
    
    2-3.解析案例(Get)

    Json解析

    using LitJson;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using UnityEngine;
    using UnityEngine.Networking;
    using UnityEngine.UI;
    
    public class JsonRead : MonoBehaviour {
    
        public People[] p;
        public People p1,p2,p3;
        public Text[] nameA;
        public Text[] ageA;
        public RawImage[] imgA;
        void Start () {
            p = new People[] {
             p1 = new People(),
             p2 = new People(),
             p3 = new People()
            };
            // 内容获取到了
            ReadJson();
        
            ShowPeople(0);
            ShowPeople(1);
            ShowPeople(2);
        }
    
        public void ShowPeople(int id)
        {
            nameA[id].text = p[id].name;
            ageA[id].text = p[id].age.ToString();  
            StartCoroutine(LoadImage(p[id].imgUrl, id));       
        }
    
        public void ReadJson()
        {
            string path = "Assets/Resources/TextFile.txt";
            string textOne = File.ReadAllText(path);
            JsonData data = JsonMapper.ToObject(File.ReadAllText(path));
            for (int i = 0; i < data.Count; i++)
            {
                JsonData idValue = data[i]["id"];
                p[i].id = int.Parse(idValue.ToString());
                JsonData AgeValue = data[i]["age"];
                p[i].age = int.Parse(AgeValue.ToString());
                JsonData nameValue = data[i]["name"];
                p[i].name = nameValue.ToString();
                JsonData imgUrlValue = data[i]["img"];
                p[i].imgUrl = imgUrlValue.ToString();
                Debug.Log("imgUrl :" + imgUrlValue.ToString());       
            }    
        }
    
        IEnumerator LoadImage(string url,int id)
        {
            UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
            yield return www.SendWebRequest();
            if (www.isHttpError)  {
                Debug.Log("连接错误");
            }
            else{
                if (www.responseCode == 200)
                {
                    Debug.Log("连接成功");
                    imgA[id].texture = DownloadHandlerTexture.GetContent(www);            
                }else            {
                    Debug.Log("连接不成功");
                    // 请检查网络,或者重新刷新
                }
            }
        }
    }
    
    public class People
    {
        public int id;
        public string name;
        public int age;
        public string imgUrl;
        public People()
        {
        }
        public People(int ID,string Name,int Age,string ImgUrl, Texture2D Img)
        {
            id = ID;
            name = Name;
            age = Age;
            imgUrl = ImgUrl;
            img = Img;
        }
    }
    
    • Json数据文本TextFile
    [
    {"id" : 1,"name" : "jame","age":20,"img":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541066018995&di=98ec0d44536d82fa03ac7a2580990afc&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201602%2F06%2F20160206025901_JtzEC.thumb.700_0.jpeg"},
    {"id" : 2,"name" : "Sume","age":22,"img":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541068738551&di=d2a0b0fa09fecbb87926dd7f64e5851f&imgtype=0&src=http%3A%2F%2Fimg5q.duitang.com%2Fuploads%2Fblog%2F201311%2F30%2F20131130235032_tBLEJ.thumb.700_0.jpeg"},
    {"id" : 3,"name" : "Baye","age":25,"img":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541066038599&di=74d1aaf46dd716863a187b7952fe1072&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F7c1ed21b0ef41bd52a1399d25bda81cb39db3d57.jpg"}
    ]
    
    2-4 斗鱼API请求(Get)

    加载出来斗鱼首页的房间

    http://capi.douyucdn.cn/api/v1/live?limit=20&offset=0 
    
    using LitJson;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;
    using UnityEngine.UI;
    
    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public int error { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<DataItem> data { get; set; }
    
        public Root()
        {
            data = new List<DataItem>();
        }
    }
    
    public class DataItem
    {
        /// <summary>
        /// 
        /// </summary>
        public string room_id { get; set; }
        /// <summary>
        ///   
        /// </summary>
        public string room_src { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string vertical_src { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int isVertical { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int cate_id { get; set; }
        /// <summary>
        /// 明天15:00总决赛 IGvsFNC
        /// </summary>
        public string room_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string show_status { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string subject { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string show_time { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string owner_uid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string specific_catalog { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string specific_status { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string vod_quality { get; set; }
        /// <summary>
        /// 英雄联盟官方赛事
        /// </summary>
        public string nickname { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int online { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int hn { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string game_url { get; set; }
        /// <summary>
        /// 英雄联盟
        /// </summary>
        public string game_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int child_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string avatar { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string avatar_mid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string avatar_small { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string jumpUrl { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string fans { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int ranktype { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int is_noble_rec { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string anchor_city { get; set; }
    }
    
    public class LoadData : MonoBehaviour {
        // https://rpic.douyucdn.cn/asrpic/181102/1863767_1328_66.jpg/dy1
        // https:\/\/rpic.douyucdn.cn\/asrpic\/181102\/1863767_1328_66.jpg\/dy1
        public Root rt;
        public DataItem item;
        public Text roomName;
        public Text gameName;
        public Text manName;
        public Text onlineCount;
        void Start() {
            rt = new Root();
    
            string url = "http://capi.douyucdn.cn/api/v1/live?limit=2&offset=0";
            StartCoroutine(GetLoadRoom(url,0));   
        }
    
        public void ShowRoomMessage(int RoomID)
        {
            DataItem item = rt.data[RoomID];
            Debug.Log(item.room_name);
            roomName.text = item.room_name;
            gameName.text = item.game_name;
            onlineCount.text = item.online.ToString();
            manName.text = item.nickname;
        }
    
        IEnumerator GetLoadRoom(string url,int RoomID)
        {
            UnityWebRequest q = UnityWebRequest.Get(url);
            yield return q.SendWebRequest();
            if (q.isNetworkError)
            {
            }
            else
            {
                string str = System.Text.Encoding.Default.GetString(q.downloadHandler.data);                 
                JsonData dataJson = JsonMapper.ToObject(str);  
                // 获取 data数组内容
                for (int i = 0; i < dataJson.Count; i++)
                {
                    JsonData errorValue = dataJson["error"];
                    //赋值给rt.error
                    rt.error = int.Parse(errorValue.ToString());
                    JsonData dataList = dataJson["data"][i];
                    Debug.Log(dataList.Count);
                    rt.data.Add(JsonMapper.ToObject<DataItem>(dataList.ToJson()));              
                }
                //roomName.text = rt.data[RoomID].room_name;
                //gameName.text = rt.data[RoomID].game_name;
                //onlineCount.text = rt.data[RoomID].online.ToString();
                //manName.text = rt.data[RoomID].nickname;
                ShowRoomMessage(RoomID);
            }
        }
    }
    
    1-5 项目API请求实战(Post)


    接口类似下面这种,那么我们如何传递参数。如何传递他要求的必填参数,这就需要沟通服务器人员,我传递的参数是什么类型,怎么添加,具体可以看下面的例子,粒子中的代码你直接拿去用,是不可以的,因为参数我去掉了,参数是服务器给的如:appid,device_id,涉及公司机密。
    Post接口

    代码教会你如何发送Post请求(携带请求体),至于回来的数据你要自己处理,不要想着抄袭,一点用没有!可以将请求回来的数据保存到模型中,也可以进行Json本地存储。
    void Start () {
            // 请求数据
            string url = "http://life.jeckjian.top/index/szvideo_api/get_scenes.html";
            // 请求体
            WWWForm requestData = new WWWForm();
            // 请求体参数
            form.AddField("appid", "8888888");
            //  请求体参数
            form.AddField("device_id", "9999999");
            // 请求体中的请求类型
            form.AddField("class_type", "immersive");
             // 发送
            StartCoroutine(GetLoadData(url, requestData));
    }
    
       IEnumerator GetLoadData(string url, WWWForm requestData )
        {
            UnityWebRequest q = UnityWebRequest.Post(url, requestData );
            yield return q.SendWebRequest();
            if (q.isNetworkError)
            {
                Debug.Log(q.error);
            }
            else
            {
                 // 成功后的数据如何获取,并转换出来
                string str = System.Text.Encoding.Default.GetString(q.downloadHandler.data);
                JsonData dataJson = JsonMapper.ToObject(str);
                JsonData statusValue = dataJson["status"];
                JsonData codeValue = dataJson["code"];
                JsonData msgValue = dataJson["msg"];
                JsonData info = dataJson["info"];
                for (int j = 0; j < info.Count; j++)
                {
                    JsonData list = info["list"];
                    // 保存元素个数
                    count = list.Count;
                    // 遍历当前的场景
                    for (int k = 0; k < list.Count; k++) 
                    {                
                        JsonData listItem = list[k];
                        // 遍历场景下的数据
                        for (int i = 0; i < listItem.Count; i++)
                        {   
                            JsonData videoIDValue = listItem["szvideo_id"];                       
                            JsonData packageValue = listItem["package"];
                            JsonData snValue = listItem["sn"];
                            JsonData priceValue = listItem["price"];                 
                            JsonData titleValue = listItem["title"];                      
                            JsonData descriptValue = listItem["descript"];
                          //  Debug.Log(descriptValue.ToString());
                            JsonData imageValue = listItem["image"];                       
                            JsonData videoValue = listItem["video"];
                            JsonData _statusValue = listItem["status"];
                            JsonData class_idValue = listItem["class_id"];
                            JsonData pidValue = listItem["pid"];
                            JsonData nameValue = listItem["name"];
                            JsonData class_typeValue = listItem["class_type"];
                            JsonData package_nameValue = listItem["package_name"];
                        }                   
                    }
                }
                // 在这里数据已经全部加载完毕
                  可以存储,也可以给控件展示了。
            }
        }
    
    另一种传递参数的写法
    IEnumerator PostLoadData(string url, Dictionary<string, string> dic)
        {
            WWWForm f = new WWWForm();
            foreach (KeyValuePair<string,string> item in dic)
            {
                f.AddField(item.Key, item.Value);
            }
           UnityWebRequest q = UnityWebRequest.Post(url, f);
            yield return q.SendWebRequest();
    }
    

    三、HttpWebRequest

    3-1.代码演示

    C#中也提供了网络下载资源的方法HttpWebRequest,

    • 注意:
      在Unity中使用system.net中的HttpWebRequest获取返回信息,如果数据较大,会卡顿,主要由于unity单线程,httpwebrequest不能异步执行;
    
        string urlPath = "http://www........";   //写个网络资源路径
        string localPath = @"D:VR04\longtu.mp4";(如果是压缩就写.zip 视频就写.mp4,图片就写.jpg/.png)
    
           /// <summary>
          /// 下载文件
          /// </summary>
    
        IEnumerator DownLoadFile(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse hw = (HttpWebResponse)request.GetResponse();
            Stream stream = hw.GetResponseStream();
            FileStream fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write);
            long length = hw.ContentLength;
            long currentNum = 0;
            decimal currentProgress = 0;
     
            while (currentNum < length)
            {
                byte[] buffer = new byte[1024];
                currentNum += stream.Read(buffer, 0, buffer.Length);
                fileStream.Write(buffer, 0, buffer.Length);
                if (currentNum % 1024 == 0)
                {
                    currentProgress = Math.Round(Convert.ToDecimal(Convert.ToDouble(currentNum) /Convert.ToDouble(length) * 100), 4);
                    Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + currentNum + "字节下载进度" + currentProgress.ToString() + "%");
                }
                else
                {
                    Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" + currentNum + "字节"+ "字节 下载进度" + 100 + "%");
    
                }
                currentnn = currentProgress;
                yield return false;
            }
            hw.Close();
            stream.Close();
            fileStream.Close();
        }
        decimal currentNumShow;
        GUIStyle guistyle = new GUIStyle();
    
        void OnGUI()
        {
            guistyle.fontSize = 80;
            GUI.Label(new Rect(50, 50, 50, 50), currentNumShow.ToString(), guistyle);
        }
    
    • 欢迎购买本课程:

    腾讯课堂
    腾讯课堂
    微信小程序
    网易云课堂
    网易云课堂

    展开全文
  • unity 背包Item拖拉

    2016-10-07 21:02:40
    UGUI using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.UI;...public class Item : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerE

    UGUI

    using UnityEngine;
    using System.Collections;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    
    public class Item : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
    {
        public GameObject draggingItem;
        private RectTransform itemRect;
        public Image itemImage;
        private Transform oldSlot;
        public int itemID;
        public Text itemCount;
        void Awake()
        {
            itemImage = GetComponent<Image>();
        }
    	// Use this for initialization
    	void Start () {
            draggingItem = GameObject.FindGameObjectWithTag("DraggingItem");
    	    itemRect = GetComponent<RectTransform>();
    	}
    	
    	// Update is called once per frame
    	void Update () {
    	
    	}
    
        public void OnBeginDrag(PointerEventData eventData)
        {
            oldSlot = transform.parent;
            transform.SetParent(draggingItem.transform);
            SetDraggedPosition(eventData);
            itemImage.raycastTarget = false;
        }
    
        public void OnDrag(PointerEventData eventData)
        {
            SetDraggedPosition(eventData);
        }
    
        public void OnEndDrag(PointerEventData eventData)
        {
            Transform newSlot = null;
            if (eventData.pointerEnter == null )
            {
                transform.SetParent(oldSlot);
                transform.localPosition = Vector3.zero;
                itemImage.raycastTarget = true;
                return;
            }
            else
            {
                newSlot = eventData.pointerEnter.transform;
            }
            
            if(newSlot.tag.Equals("Slot"))
            {
                transform.SetParent(newSlot);
                transform.localPosition = Vector3.zero;
                
            }
            else if (newSlot.tag.Equals("Item"))
            {
                transform.SetParent(newSlot.parent);
                transform.localPosition = Vector3.zero;
                newSlot.SetParent(oldSlot);
                newSlot.localPosition = Vector3.zero;
            }
            else
            {
                transform.SetParent(oldSlot);
                transform.localPosition = Vector3.zero;
            }
            itemImage.raycastTarget = true;
        }
    
        private void SetDraggedPosition(PointerEventData eventData)
        {
            Vector3 worldPos;
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(itemRect, eventData.position, eventData.pressEventCamera, out worldPos))
            {
                itemRect.position = worldPos;
            }
        }
    
        public void SetItemCount(int num)
        {
            int intCount = int.Parse(itemCount.text);
            intCount += num;
            itemCount.text = intCount.ToString();
            if(intCount <= 0)
            {
                Destroy(gameObject);
                Tooltip.instance.Hide();
            }
        }
    
        public void OnPointerEnter (PointerEventData eventData)
        {
            Tooltip.instance.Show(this, KnapsackManager.instance.GetItemByID(itemID), eventData);
        }
    
        public void OnPointerExit(PointerEventData eventData)
        {
            Tooltip.instance.Hide();
        }
    
        public void OnPointerClick(PointerEventData eventData)
        {
            if(eventData.button == PointerEventData.InputButton.Left)
            {
                Slot slot = GetComponentInParent<Slot>();
                if(slot != null)
                {
                    KnapsackManager.instance.UseItem(slot.slotID);
                }
            }
        }
    }
    

    NGUI

    using UnityEngine;
    using System.Collections;
    
    public class InventoryItem : MonoBehaviour
    {
        [HideInInspector]
        public GameObject draggingItem;
        public UISprite itemIcon;
        public UILabel itemCount;
        [HideInInspector]
        public Transform oldSlot;
        private Collider itemCollider;
        public int itemID;
        public int count = 1;//叠加数量
    	// Use this for initialization
    	void Start () {
    	    itemCollider = GetComponent<BoxCollider>();
            draggingItem = GameObject.FindGameObjectWithTag("DraggingItem");
    	}
    	
    	// Update is called once per frame
    	void Update () {
    	
    	}
    
        public void OnDragStart()
        {
            oldSlot = transform.parent;
            transform.SetParent(draggingItem.transform);
            itemCollider.enabled = false;
    
            NGUITools.MarkParentAsChanged(gameObject);
        }
    
        public void OnDrag(Vector2 delta)
        {
            transform.localPosition += (Vector3)delta;
        }
    
        public void OnDragEnd()
        {
            Transform newSolt = UICamera.hoveredObject.transform;
            if(newSolt.tag == "Slot")
            {
                transform.SetParent(newSolt);
                transform.localPosition = Vector3.zero;
            }
            else if(newSolt.tag == "InventoryItem")
            {
                transform.SetParent(newSolt.parent);
                transform.localPosition = Vector3.zero;
                newSolt.SetParent(oldSlot);
                newSolt.localPosition = Vector3.zero;
            }
            else if(newSolt.tag == "EquipmentSlot")
            {
                EquipmentSlot equipmentSlot = newSolt.GetComponent<EquipmentSlot>();
                ItemBase itemBase = ItemManager.instance.GetData(itemID);
                if (itemBase.itemType == ItemType.Equip && ((ItemEquipment)itemBase).itemJob == PlayerInfo.instance.playerIndex && equipmentSlot.itemPart == ItemManager.instance.GetItemPartByID(itemID))
                {
                        EquipmentManager.instance.AddItem(itemID);
                        Destroy(draggingItem.transform.GetChild(0).gameObject);
                }
                else
                {
                    transform.SetParent(oldSlot);
                    transform.localPosition = Vector3.zero;
                }
            }
            else if (newSolt.tag == "EquipmentItem")//换装(已经有装备)
            {
                EquipmentSlot equipmentSlot = newSolt.parent.GetComponent<EquipmentSlot>();
                ItemBase itemBase = ItemManager.instance.GetData(itemID);
                if (itemBase.itemType == ItemType.Equip && ((ItemEquipment)itemBase).itemJob == PlayerInfo.instance.playerIndex && equipmentSlot.itemPart == ItemManager.instance.GetItemPartByID(itemID))
                {
                    EquipmentItem oldItem = newSolt.GetComponent<EquipmentItem>();
                    InventoryManager.instance.AddItem(oldItem.itemID, 1);
                    EquipmentManager.instance.RemoveItem(oldItem.itemID);
    
                    EquipmentManager.instance.AddItem(itemID);
                    Destroy(draggingItem.transform.GetChild(0).gameObject);
                    
                }
                else
                {
                    transform.SetParent(oldSlot);
                    transform.localPosition = Vector3.zero;
                }
            }
            else
            {
                transform.SetParent(oldSlot);
                transform.localPosition = Vector3.zero;
            }
            itemCollider.enabled = true;
        }
    
        public void SetItemCount(int num)
        {
            count += num; 
            itemCount.text = count.ToString();
        }
    }
    


    展开全文
  • unity UGUI 动态添加item

    千次阅读 2016-10-11 10:07:18
    unity UGUI 动态添加item 时,要注意设置item的 LocalScale ,否则会变形

    unity UGUI 动态添加item 时,要注意设置item的 LocalScale ,否则会变形

      public void InitShopItem()
         {
           foreach(KeyValuePair<int,EquipShopItemData> kv in datas)
           {
               GameObject item = Instantiate(shopItemPrefab);
               item.transform.SetParent(shopItemParent);
               //设置本地缩放大小,消除变形
               item.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
               ShopItemUI shopItemUI = item.GetComponent<ShopItemUI>();
               ItemEquipment equiItem = (ItemEquipment)BaseItemMangager.instance.GetData(kv.Value.itemID);
               if (shopItemUI != null)
               {
                   shopItemUI.SetShopItemUI(equiItem.itemIcon, equiItem.itemName, equiItem.itemBuy, equiItem.itemSell,equiItem.itemID);
               }
           }        
         }


    展开全文
  • jsondata遍历解析key,value unity

    千次阅读 2018-12-04 14:27:19
    JsonData jd = new JsonData(); JsonData modeInfo = JsonMapper.ToObject(jsonD); if (modeInfo.ContainsKey("texFiles")) { IDictionary dic = modeInfo; foreach (var item in dic.Values) { IDictionary ...
    var jsonD = {
    	"texFiles": {
    		"沙发_03_01.jpg": "u6c99u53d1u005fu0030u0033u005fu0030u0031u002eu006au0070u0067",
    		"纯色黑白灰.jpg": "u7eafu8272u9ed1u767du7070u002eu006au0070u0067",
    		"沙发_03_02.jpg": "u6c99u53d1u005fu0030u0033u005fu0030u0032u002eu006au0070u0067",
    		"沙发_03_03.jpg": "u6c99u53d1u005fu0030u0033u005fu0030u0033u002eu006au0070u0067"
    	}
    }
    
    JsonData jd = new JsonData();
    JsonData modeInfo = JsonMapper.ToObject(jsonD);
    if (modeInfo.ContainsKey("texFiles")) { 
    	IDictionary dic = modeInfo;
    	foreach (var item in dic.Values)
    	{
    	   IDictionary ite = item as IDictionary;
    	   foreach (var temp in ite.Keys)
    	   {
    	       jd[temp.ToString()] = ite[temp].ToString();
    	       Debug.Log("keys: "+temp+"---"+"values: "+ ite[temp]);
    	   }
    	}
    }
    
    展开全文
  • Unity 中操作数据文件

    2020-01-27 20:02:06
    Resources文件夹是Unity里自动识别的一种文件夹,可在Unity编辑器的Project窗口里创建,并将资源放置在里面。Resources文件夹下的资源不管是否有用,全部会打包进.apk或者.ipa,并且打包时会将里面的资源压缩处理。...
  • 如果有更好实现的方式,麻烦请告知,网上看无限滑动的例子很多都是动态增减item,我这个是改变每个item的位置来实现无限滑动。 此为Lua代码 local ImageCarousel = class("ImageCarousel") function Image...
  • 最近要采集一些数据,原来是读取MySQL到没有什么问题,现在改成数据库是SQLServer,但是一直报找不到System.Data.dll文件的错误,在这里记录一下解决方法,供以后避坑...2、没放System.Data.dll到项目中的unity错误信
  • unity xcharts

    千次阅读 2020-10-12 23:52:36
    using System.Collections;...using System.Data; using UnityEngine.UI; using System.Windows.Forms; public class Thrush : MonoBehaviour { // Use this for initialization DataTable dt...
  • Unity动画生成工具

    千次阅读 2019-07-04 22:05:06
    [UnityEditor.MenuItem("Tools/AnimatorGenerator")] private static void Open() { var window = GetWindow(); window.position = GUIHelper.GetEditorWindowRect().AlignCenter(450, 500); } [InlineEditor...
  • 【游戏开发创新】使用Unity制作Unity题库,支持题目录入和刷题(面试 | 笔试)
  • 首先了解一下,Unity的地形系统Terrain的地形相关数据是存放在TerrainData里的 而关于地形的高低起伏数据,是存储在TerrainData中的HeightMap中。 通常在新建地形的时候,我们就已经确定了HeightMap的分辨率 ...
  • using UnityEngine; using System.Collections... } public void OnPointerClick(PointerEventData eventData) { if (onClick != null) { onClick(gameObject); } } } 注意: 当父物体上有button组件时,子部件不会响应
  • Unity ScrollView特效裁切最佳方法

    千次阅读 2020-07-28 22:54:39
    Scrollview在开发过程中非常常见,背包、成就、排行榜等一些功能都会遇到,平时的使用过程中可能还好,不会出太多问题,可是一旦策划要在里面的item上增加特效,问题就来了,因为粒子不会被裁切,导致滑动过程中出现...
  • Unity中启动Android Activity并传参源起在AndroidStudio中创建工程 源起 项目中原来的谷歌登录是Unity插件的形式添加的,现在要改成在Android中调用,要求不能继承UnityPlayerActivity,于是乎就开始查资料,花了四...
  • 文章目录一、前言二、原理三、最终实现效果四、具体使用1、循环列表脚本:RecyclingListView2、列表item脚本:RecyclingListViewItem3、测试脚本五、附录1、RecyclingListView.cs2、RecyclingListViewItem.cs ...
  • Unity 中生成JSON以及对应的解析方法

    千次阅读 2017-09-21 17:01:18
    //遍历JsonData的key由于JsonData实现了IDictionary接口,所以可以使用Foreach进行遍历 IDictionary dic = jsdata1 as IDictionary; foreach ( string item in dic.Keys) { Debug.Log(item); } //=...
  • Unity 编辑器扩展(一) —— 自定义Unity面板 自定义Menu菜单 MenuItem 特性 MenuItem 属性可以向主菜单和上下文菜单添加菜单选项。 public MenuItem(string itemName); public MenuItem(string itemName, bool ...
  • Unity大密度建筑场景加载解决方案

    万次阅读 多人点赞 2018-09-07 09:41:09
    现在虚拟城市仿真,以及军事仿真项目越来越多,开发此类项目,首先面对...Unity官方提供了Occlusion Culling的裁剪操作,网上有很多文章对它做了相关介绍,因为它是Unity自身提供的,对于我们程序员来说就是一个黑盒...
  • 1、如何用代码初始化下拉菜单的items 2、如何乱序加载items 3、如何读取当前选中的item的值
  • Unity答题系统

    热门讨论 2021-11-29 16:39:12
    /// /// 提交事件 /// private void submitClick() { //遍历当前题目的选项,有选择的就可以提交核验答案,并显示解析内容 foreach (var item in options) { if (item.thisToggle.isOn) { rightAnswer = "";...
  • 首要条件 需要创建一个模板类(必须要有的), 里面的属性名和json里面的属性名一样(当然也可以不一样) ... //data是通过UnityWebRequest获取到的数据 public void SingDate(string data) { JObject obj =
  • Unity3D日常开发】解析Txt文档,赋值给Text案例

    千次阅读 多人点赞 2021-06-08 11:43:47
    有小伙伴跟我说,公司现在需要解析JSON,但是百度的解析JSON的又各种各样,我都看懵了,有没有好一点的解析方案,然后我就将我这篇文章推送给了他【Unity3D日常】Unity写Json数据,以及在Unity读取、解析Json数据。...
  • 【游戏开发实战】Unity从零做一个任务系统(含源码工程 | 链式任务 | 主线任务 | 分支任务)
  • Unity Dots学习

    2021-02-13 23:06:38
    我用的Unity版本是Unity 2019.4.19f1c1 (64-bit) Unity中的PacketManager中下载Entities,再下载Hybrid Rer用于显示。 Dots入门 1.打印一个数字 先创建一个Component using System.Collections; using System....
  • 一般我们与后端对接的时候会用到UnityWebRequest这里简单使用这个与后端进行交互这个是总类using UnityEngine;using System.Collections;using System.Collections.Generic;using System;using UnityEngine....
  • Unity3D进阶4-12】Unity3D 对话系统

    千次阅读 2020-06-19 17:31:42
    一、目录 【Unity3D从入门到进阶】文章目录及设置这个专栏的初衷
  • 浅谈Unity中的优化

    千次阅读 2020-11-25 09:50:10
    文章目录0-前言1-GC介绍1.1-脑图1.1-介绍1.2-Unity内存管理机制简介1.3-栈内存分配和回收机制1.4-堆内存分配和回收机制1.5-垃圾回收时的操作1.6-何时会触发垃圾回收1.7-GC操作带来的问题2-GC分析及优化2.1-分析GC...
  • Unity Windows 路径长度限制踩坑

    千次阅读 2020-04-27 17:21:01
    错误日志 今天在 Windows 上打 PC 包时遇到了这样的报错: ...IOException: Failed to Move File / Directory from 'Temp/StagingArea\bunny rummy_Data\StreamingAssets\lua\logic\ui\pnl_activity\first_add_...
  • Unity3D插件分享 简书地址 我的个人博客 QQ群:1040082875 ❤ 一、前言 最近,有粉丝问我: 粉丝:“怎么用单例模式呀?” 我:“https://blog.csdn.net/weixin_43430200/article/details/107459447” 粉丝:“我...
  • Unity Json解析实例

    2019-11-23 14:20:55
    // 读取 JsonMapper.ToObject(mainHoist.text)); private void MainHoistAnalysis(JsonData jsonData) { string[] infos = new string[2]; List<string[]> strList = ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,560
精华内容 1,424
关键字:

unitydataitem