当前位置:网站首页>Unity learning day14 -- collaboration and WWW
Unity learning day14 -- collaboration and WWW
2022-06-23 12:39:00 【First wife ash yuanai】
coroutines IEnomerator
1.yield return Stop the program , Wait until the current frame ends , Continue at the next frame
yield break End of Association
2.StartCoroutine() Start the coroutines
3.yield return new WaitForEndOfFrame() At the next frame OnGUI After the execution, resume the execution
4.yield return new WaitForSeconds(n) Stop the program , etc. n Seconds later
5.yield return new WaitForFixedUpdate() stay FixedUpdate After performing
6.yield return StartCoroutine( Another process ) Coroutines nesting , Execute the current process after another process is completed
How to start the process :3 Heavy haul
StartCoroutine( The name of the project ( Co process parameters ))
StartCoroutine(" Method name ")
StartCoroutine(" Method name ", Method parameter ) Start the process in this way , The parameter can only be one
The way to stop the process :
StopCoroutine(Coroutine) Coroutine Is the value object returned by the coroutine
StopCoroutine(IEnumerator) IEnumerator Is a coroutine interface object
StopCoroutine(" Co process method name ") This method can only stop the coroutine starting with a string , This is the second startup process
StopAllCoroutines Stop all processes - Use with caution
Jump out of the process :
yield break
Special synergy
IEnumerator Start() take Start Transform it into a collaborative process Start automatically at the beginning of the game
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IEDemo : MonoBehaviour
{
int NormalFunction()
{
//return The meaning is 【 Return results , And end the execution of the function 】
return 1;
}
// Collaborative process --> 【 Special return value type (Ienumerator Methods 】
IEnumerator IEnumeratorDemo()
{
Debug.Log("1");
// The return value of a coroutine is the same as that of a common method 【 difference 】
// The biggest difference between , When a coroutine returns the keyword used [yield return]
// Anything can be returned
// In the process of cooperation [ At least once ] Of yield return
//yield return [ Known values or variables ] The meaning is
//【 Pause method execution , Wait for the end of the current frame , Wait for the next frame to continue 】
yield return 1;
Debug.Log(2);
// Stop the process
yield break;
// Pause
yield return null;
Debug.Log(3);
// Pause
yield return "abc";
Debug.Log(4);
}
IEnumerator WaitForSecondsDemo()
{
Debug.Log("Dog");
// meaning : Stop the program , etc. 3 Seconds later , Keep going
yield return new WaitForSeconds(3);
Debug.Log("Cat");
}
IEnumerator WaitForEndOfFrameDemo()
{
Debug.Log("abc");
// At the next frame Update After the execution, resume the execution
//yield return null;
// meaning : Stop the program , Wait for the next frame to continue
// At the next frame OnGUI After the execution, resume the execution
yield return new WaitForEndOfFrame();
Debug.Log("def");
}
IEnumerator WaitForSecondCircle()
{
int count = 0;
while (true)
{
yield return new WaitForSeconds(1);
Debug.Log(++count);
}
}
IEnumerator InvokeMethodPerSeconds(Action method,float seconds)
{
while (true)
{
// Execute function
method();
// Waiting time
yield return new WaitForSeconds(seconds);
}
}
IEnumerator InvokeMethodPerFrame(Action method)
{
while (true)
{
method();
yield return 0;
}
}
private void Start()
{
// Call ordinary functions
NormalFunction();
// Start the collaboration program
// The first way to write it
//StartCoroutine(IEnumeratorDemo());
// The second way , Write separately
/*IEnumerator ie = IEnumeratorDemo();
StartCoroutine(ie);*/
//StartCoroutine(WaitForEndOfFrameDemo());
//StartCoroutine(WaitForSecondsDemo());
//StartCoroutine(WaitForSecondCircle());
/*StartCoroutine(InvokeMethodPerSeconds(() =>
{
Debug.Log("Hello World!");
}, 2f));*/
StartCoroutine(InvokeMethodPerFrame((() =>
{
Debug.Log("Hello Unity!");
})));
}
}
Get The way : The information parameters are displayed in URL in
Post The way : Parameter information is not displayed in URL in
WWW
using System;
using System.Collections;
using System.IO;
using System.Net;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;
public class WWWDemo : MonoBehaviour
{
[Header(" Original component ")]
public RawImage _rawImage;
[Header("Image Components ")]
public Image _image;
[Header(" Video player ")]
public VideoPlayer _VideoPlayer;
// Declare a video clip
private VideoClip _videoClip;
private IEnumerator Start()
{
//yield return StartCoroutine(DownLoadText());
//yield return StartCoroutine(DownloadNewsText());
//yield return StartCoroutine(DownloadTexture());
// yield return StartCoroutine(NewVisonDownload());
yield return StartCoroutine(NewVersionDownloadVideo());
}
/// <summary>
/// Download the text
/// </summary>
/// <returns></returns>
IEnumerator DownloadNewsText()
{
WWW www = new WWW("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
// Waiting for download , The first one is
yield return www;
// Print the results
Debug.Log(www.text);
}
/// <summary>
/// New version download video
/// </summary>
/// <returns></returns>
IEnumerator NewVersionDownloadVideo()
{
// Try loading the video clip
_videoClip = Resources.Load<VideoClip>("welcome");
// If not loaded to , Then go to download
if (_videoClip==null)
{
// Create a network request object
UnityWebRequest webRequest = UnityWebRequest.Get("http://f.video.weibocdn.com/00341gCFgx07LoEZcDa7010412017MOB0E010.mp4?label=mp4_hd&template=852x480.25.0&trans_finger=62b30a3f061b162e421008955c73f536&media_id=4619091051479108&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=3&ot=h&lp=00002KCE4n&ps=4pdsh0&uid=3ZoTIp&ab=3915-g1,966-g1,1493-g0,1192-g0,1191-g0,1046-g2,3601-g5,1258-g0&Expires=1619087600&ssig=V%2FxM%2B1IoMo&KID=unistore,video");
//WebRequest webRequest = WebRequest.Create(
//"http://f.video.weibocdn.com/00341gCFgx07LoEZcDa7010412017MOB0E010.mp4?label=mp4_hd&template=852x480.25.0&trans_finger=62b30a3f061b162e421008955c73f536&media_id=4619091051479108&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=3&ot=h&lp=00002KCE4n&ps=4pdsh0&uid=3ZoTIp&ab=3915-g1,966-g1,1493-g0,1192-g0,1191-g0,1046-g2,3601-g5,1258-g0&Expires=1619087600&ssig=V%2FxM%2B1IoMo&KID=unistore,video");
// Send network request , And wait for download
webRequest.SendWebRequest();
while (!webRequest.isDone)
{
Debug.Log(webRequest.downloadProgress);
yield return 0;
}
// Get byte stream of video file
byte[] bytes = webRequest.downloadHandler.data;
// Write to local
File.WriteAllBytes(Application.dataPath + "/Resources/welcome.mp4",bytes);
while (_videoClip == null)
{
// Refresh resources
AssetDatabase.Refresh();
// Try loading the video clip
_videoClip = Resources.Load<VideoClip>("welcome");
yield return 0;
}
}
// Will be a good video , Set to ViedeoPlayer In the component
_VideoPlayer.clip = _videoClip;
// Play the video
_VideoPlayer.Play();
}
/// <summary>
/// New version download
/// </summary>
/// <returns></returns>
/// First step 、 Create objects :UnityWebRequest
/// Get:UnityWebRequest.Get(url)
/// Post:UnityWebRequest.Post(url, parameter list )
/// The second step 、 send out web situation , And wait for download
/// yield return data.SendWebRequest();
/// The third step 、 Get downloaded content
/// Content classification : Text Text Direct use ; Byte stream Bytes Need to write to local file
/// Step four 、 How to write to local
/// File.WriteAllBytes( The full path to the file , Bit array )
/// 【 Example 】
/// File.WriteAllBytes(Application.dataPath + "/a.text",bytes);
/// Step five 、 How to get files locally
/// 1. file
IEnumerator NewVisonDownload()
{
UnityWebRequest data = UnityWebRequest.Get("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
// send out web request , And wait for download
yield return data.SendWebRequest();
// data 【 Byte stream 】
byte[] bytes = data.downloadHandler.data;
// Write byte stream to local Resources In the folder
File.WriteAllBytes(Application.dataPath + "/Resources/a.text",bytes);
// Wait a frame
yield return 0;
// Refresh resources
AssetDatabase.Refresh();
// from Resources Read files in the folder
Resources.Load<Text>("a");
}
/// <summary>
/// Download the pictures
/// </summary>
/// <returns></returns>
IEnumerator DownloadTexture()
{
WWW www = new WWW("https://th.bing.com/th/id/R65398d6ad86129f9628c0ad80da4040c?rik=C3qNS9mZOQk%2b5A&riu=http%3a%2f%2fwww.shijuepi.com%2fuploads%2fallimg%2f200918%2f1-20091Q10420.jpg&ehk=QBNuJIbVP1qo%2bwUD3YzXcvL4H5iHivOHXUnzzRw%2bWfU%3d&risl=&pid=ImgRaw");
// The second kind , Waiting for download
while (!www.isDone)
{
Debug.Log("progress:" + www.progress);
yield return 0;
}
/*// Waiting for download
yield return www;*/
#region Use the texture directly RawImage Rendering
// Set the original width and height of the picture
_rawImage.GetComponent<RectTransform>().sizeDelta =
new Vector2(www.texture.width,www.texture.height);
// Set picture to RawImage in
_rawImage.texture = www.texture;
#endregion
#region Use Image To render , Before that, you need to convert the texture into a sprite
Sprite sprite = Sprite.Create(www.texture, new Rect(
Vector2.zero,
new Vector2(www.texture.width,
www.texture.height)),
Vector2.zero
);
sprite.name = "sprite";
// Rendering
_image.sprite = sprite;
#endregion
// How to convert textures into sprites
}
/// <summary>
/// Download Video
/// </summary>
/// <returns></returns>
IEnumerator DownloadVideos()
{
WWW www = new WWW("");
yield return www;
//www.get
}
}
边栏推荐
- Runtime application self-protection (rasp): self-cultivation of application security
- 一个 BUG 开发表示用户不会这样操作,无需修复,测试人员如何应对?
- 【系统架构】-软件架构的5大风格
- Unity小需求——简单实现仿王者钻石夺宝(单抽)
- 【UVM入门 ===> Episode_7 】~ sequence、sequence item、sequencer、driver
- What should I do if a serious bug occurs within the scope of my own test and I am about to go online?
- Capacitated Facility Location Problem容量有限设施选址问题
- 夏日炎炎玩转新加坡:盘点室内景点和夜游好去处
- ROS knowledge: point cloud files PCD format
- C#学习(高级课程)Day13——反射
猜你喜欢

解决:Argument type ‘String‘ expected to be an instance of a class or class-constrained type

What are the criteria for judging the end of the test?

Go zero micro Service Practice Series (VI. cache consistency assurance)

20年上海站D题Walker(二分,简洁)

项目测试一半,需求要变更,测试人员怎么办?

Blue Bridge Cup single chip microcomputer (I) -- turn off peripherals and turn off led

「开发者说」钉钉连接器+OA审批实现学校学生假勤场景数字化

mysql innodb的redo log buffer中未commit的事务持久化到redo log后,万一事务rollback了怎么办?

Deveco device tool helps openharmony device development

QT5知识:QT绘制图形
随机推荐
20年上海站D题Walker(二分,简洁)
C#部分——值类型和引用类型
CSS magic nugget mug; Optimization of CK, ES and redisearch schemes in ten million level data query; Why does module circular dependency not lead to dead loop Sauced afternoon tea issue 13
Photon网络框架
全新项目,如何保证测试的覆盖率?
跟循泰国国内游宣传曲MV,像本地人一样游曼谷
Want to learn ETS development? Teach you to develop an iq-eq test application
机器学习系列5:距离空间(1)
Halcon原理:auto_threshold算子
kubernetes comfig subpath
语音模块:pyttsx变声项目
LinkedList 5-141. Circular linked list
现在开户有优惠吗?手机开户安全么?
Capacitated Facility Location Problem容量有限设施选址问题
Playing in Singapore in the hot summer: an inventory of indoor attractions and good places for night trips
[system architecture] - five styles of software architecture
Huawei cloud gaussdb heavily released HTAP for commercial use, defining a new paradigm of cloud native database 2.0
The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
用户行为建模
ROS知识:读取点云数据文件
