C#里怎么使用协程:IEnumerator /yield return/ StartCoroutine

void 一个函数名(){
StartCoroutine(“TryTryThis()”);
}
IEnumerator TryTryThis(){
一些内容;
yield return 一些内容; // or yield return StartCoroutine(MyFunc);
other;
}

void Fun()
{
	while(true)
	{
	 debug.log("进入循环")
	}
}

那么会一直进入循环。

但是如果把这个Fun()的类型,改为IEnumerator,

IEnumerator  Fun()
{
	while(true)
	{
	 debug.log("进入循环")
	}
}

然后想要调用这个迭代接口(IEnumerator ),就再其他函数中,写StartCoroutine(Fun())

void Start()
{
	StartCoroutine(Fun());
}

IEnumerator  Fun()
{
	while(true)
	{
	 debug.log("进入循环")
	}
}

yield return 语句的用处很广,它的主要作用是在合适的时间给你一定的返回结果。比如如果在这里运用一个yield return new WaitForSeconds(0.5f);,也就是说,这个名叫Fun()的循环中,有0.5f可以供其他代码运行。每循环一次,每输出一次“进入循环",就有0,5秒,可以让其他代码行走。所以即使是无限循环,进程也不会卡死。

这就是协程:Coroutine.


举个例子,在Unity中,要写一个迭代接口IENUMERATOR,

void Start()
{
	string[]messages={"a","b","c","d","e","f","g","h","i"};
	StartCoroutine(Fun(messages,9.5f));
}

IEnumerator  PrintMessages(string[]messages,float delay)
{
	foreach (string msg in messages
	{在对每一个messages数据串里面的内容foreach循环时,都要间隔delay秒。
		printf("已阅读一条");
		yield return new WaitForSeconds(delay);
	}
}

在这个例子,IENUMERATOR制造循环,StartCoroutine调用循环。


void Update()
{
	if(Input.GetKeyDown(KeyCode.space)
	{
		StartCoroutine(Move(Random.Position随机一个位置,8));
	}
	
}

IEnumerator  Move( Vector3 destination,float speed)
{
	while(transform.position!=destination)
	{
	transform.position=Vector3.MoveTowards(transform.position,destination目标位置,speed*time.deltatime);
	}
	yield return null;每次循环一次后,暂缓一帧再执行,预防瞬间移动
}

物体向目标移动:再次利用迭代接口IEnumerator建立一个while循环:从transform.position出发,向着目标移动,一次移动固定的距离,移动到了,结束while循环。


再举个例子,对象池管理子弹,原本想利用list的方式,每次调用pool内的list[0],然后把GameObject给bullet预设体。但是问题是,虽然它可以生成新的子弹预设体,也可以按需消失。但是它无法移动。不是很方便,只能叠在生成位置,也就是枪口上。

于是用了这个方法。

public void returnBullet(Projectile targetBullet)
    {
		StartCoroutine(returnBulletToPoolLater(targetBullet));
    }
	
	IEnumerator returnBulletToPoolLater(Projectile targetBullet)
    {Projectile是写挂载在bullet上面的脚本。在这个脚本下生成一个targetBullet
		yield return new WaitForSeconds(3f);
		三秒一个循环。
		if (targetBullet != null)
		如果子弹非空
			bulletPool.ReturnInstance(targetBullet, poolPositon);
			那么就要在poolPosition上制造一个子弹(targetBullet)
	}


配置在Gun上面的Gun.cs全文如下:

 
 
	public UnityEvent OnShoot;
	public Transform muzzle;
	[Header("Bullet Setting")]
	public Projectile projectile;
	public float msBetweenShots = 100;  //子弹发射间隔
	public float muzzleVelocity = 35;  //子弹速度
	public int bulletNumber;          //一个弹夹子弹数
	protected float nextShotTime;
	[Header("BulletPool")]
	public Transform poolPositon;
	public ObjectPool bulletPool;

	public GameObject fireEffect;
    private void Start()
    {
		poolPositon = GameObject.FindGameObjectWithTag("BulletPool").transform;
		带有BulletPool的TAG的物体,把这种物体的位置传给PoolPosition.
    }
    public virtual void GenerateBullet()
    {
		
	}
	public virtual void Shoot()
	{
        if (Time.time > nextShotTime)
        {
            nextShotTime = Time.time + msBetweenShots / 1000;
            OnShoot.Invoke();nvoke是延时调用函数
            GenerateBullet();
            其他cs里设定了,左键,激发这个脚本里面的Shoot 
        }
	}
	public void returnBullet(Projectile targetBullet)
    {
		StartCoroutine(returnBulletToPoolLater(targetBullet));
    }
	
	IEnumerator returnBulletToPoolLater(Projectile targetBullet)
    {
		yield return new WaitForSeconds(3f);
		if (targetBullet != null)
			bulletPool.ReturnInstance(targetBullet, poolPositon);
	}
	public void returnHitBulletToPool(Projectile targetBullet)
    {
		targetBullet.gameObject.SetActive(false);
		//if (targetBullet != null)
			//bulletPool.ReturnInstance(targetBullet, muzzle);
	}
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Unity C# 代码示例,用于与 OpenAI GPT-3 的 API 进行通信,以获得 AI 回复: ```csharp using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class OpenAIChat : MonoBehaviour { public string apiKey; public string prompt; public int maxTokens; public float temperature; public Text responseText; private const string API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions"; public void SendRequest() { StartCoroutine(GetResponse()); } private IEnumerator GetResponse() { var requestJson = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + ", \"temperature\": " + temperature + "}"; var request = UnityWebRequest.Post(API_URL, requestJson); request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Authorization", "Bearer " + apiKey); yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError) { Debug.LogError(request.error); yield break; } var responseJson = request.downloadHandler.text; var response = JsonUtility.FromJson<OpenAIResponse>(responseJson); if (response.choices == null || response.choices.Length == 0) { Debug.LogError("Invalid response from OpenAI API"); yield break; } responseText.text = response.choices[0].text; } [System.Serializable] public class OpenAIResponse { public Choice[] choices; } [System.Serializable] public class Choice { public string text; public float logprobs; public float finishReason; } } ``` 要使用此代码,请将其添加到 Unity 游戏对象上,并在编辑器中设置 API 密钥、提示、最大标记和温度。然后,在您的 UI 上添加一个按钮或其他交互元素,以调用 SendRequest 方法并显示响应文本。 请注意,此示例使用 UnityWebRequest 类与 OpenAI API 进行通信。您还可以使用其他网络库,如 HttpClient 或 RestSharp。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值