coroutine

4/23/2023 xlua

https://docs.unity3d.com/ScriptReference/Coroutine.html (opens new window)

https://docs.unity3d.com/ScriptReference/WaitForSeconds.html (opens new window)

接口

StartCoroutine(funtion,...)

	1.lua function
	2.lua function parameters
	return:cs_coroutine,instance
function is parameterless
Create a coroutine and return the coroutine controller and coroutine instance	

coroutine.yield(time)

UnityEngine.WaitForSeconds

cs_coroutine.stop(instance)

stop the coroutine

example:

Every time wait for 1s, the 5th second, stop the coroutine

Coroutine (无参数)

function Start()
	--cs_coroutine: Unity 协程
	--testCo 协程启动后返回值
	cs_coroutine, testCo = StartCoroutine(test)
end

function test()
	log('coroutine a started')
	count =0
	while true do
		coroutine.yield(UnityEngine.WaitForSeconds(1))
		count=count+1
		log('i am coroutine '..tostring(count))       
		if count ==5 then
			break
		end
	end
	
	cs_coroutine.stop(testCo)
	testCo = nil
	log('coroutine a stoped')

end

function OnDestroy()
	if testCo~=nil and cs_coroutine~=nil then
	 cs_coroutine.stop(testCo)
	end
	 log('OnDestroy')
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Coroutine passing parameters(带参数)

local test1=function(x,f)
	print('coroutine a started',x,f) --coroutine a started    12    hello

	coroutine.yield(UnityEngine.WaitForSeconds(1))
	print('coroutine b finish')

	coroutine.yield(CS.UnityEngine.WaitForSeconds(1))
	print('i am coroutine a')
end

function Start()
	StartCoroutine(test1,12,"hello")
end
1
2
3
4
5
6
7
8
9
10
11
12
13
Last Updated: Sun, 23 Apr 2023 06:51:08 GMT