1 Star 1 Fork 0

凉鞋/ActionKit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ActionKit.cs 164.73 KB
一键复制 编辑 原始数据 按行查看 历史
凉鞋 提交于 2022-04-24 16:04 . 新增一堆新的 API
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442
/****************************************************************************
* Copyright (c) 2018 ~ 2022 liangxiegame UNDER MIT LICENSE
*
* https://qframework.cn
* https://github.com/liangxiegame/QFramework
* https://gitee.com/liangxiegame/QFramework
*
* Latest Update: 2022.4.24 16:01 Add new API
****************************************************************************/
using QFramework.ActionKitSingleFile.Dependency.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
using System.Reflection;
namespace QFramework
{
#if UNITY_EDITOR
// v1 No.164
[ClassAPI("4.ActionKit", "ActionKit", 0, "ActionKit")]
[APIDescriptionCN("Action 时序动作序列(组合模式 + 命令模式 + 建造者模式)")]
[APIDescriptionEN("Action Sequence (composite pattern + command pattern + builder pattern)")]
#endif
public class ActionKit : Architecture<ActionKit>
{
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("延时回调")]
[APIDescriptionEN("delay callback")]
[APIExampleCode(@"
Debug.Log(""Start Time:"" + Time.time);
ActionKit.Delay(1.0f, () =>
{
Debug.Log(""End Time:"" + Time.time);
}).Start(this); // update driven
// Start Time: 0.000000
---- after 1 seconds ----
---- 一秒后 ----
// End Time: 1.000728
")]
#endif
public static IAction Delay(float seconds, Action callback)
{
return QFramework.Delay.Allocate(seconds, callback);
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("动作序列")]
[APIDescriptionEN("action sequence")]
[APIExampleCode(@"
Debug.Log(""Sequence Start:"" + Time.time);
ActionKit.Sequence()
.Callback(() => Debug.Log(""Delay Start:"" + Time.time))
.Delay(1.0f)
.Callback(() => Debug.Log(""Delay Finish:"" + Time.time))
.Start(this, _ => { Debug.Log(""Sequence Finish:"" + Time.time); });
// Sequence Start: 0
// Delay Start: 0
------ after 1 seconds ------
------ 1 秒后 ------
// Delay Finish: 1.01012
// Sequence Finish: 1.01012
")]
#endif
public static ISequence Sequence()
{
return QFramework.Sequence.Allocate();
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("延时帧")]
[APIDescriptionEN("delay by frameCount")]
[APIExampleCode(@"
Debug.Log(""Delay Frame Start FrameCount:"" + Time.frameCount);
ActionKit.DelayFrame(1, () => { Debug.Log(""Delay Frame Finish FrameCount:"" + Time.frameCount); })
.Start(this);
ActionKit.Sequence()
.DelayFrame(10)
.Callback(() => Debug.Log(""Sequence Delay FrameCount:"" + Time.frameCount))
.Start(this);
// Delay Frame Start FrameCount:1
// Delay Frame Finish FrameCount:2
// Sequence Delay FrameCount:11
// --- also support nextFrame
// --- 还可以用 NextFrame
// ActionKit.Sequence()
// .NextFrame()
// .Start(this);
//
// ActionKit.NextFrame(() => { }).Start(this);
")]
#endif
public static IAction DelayFrame(int frameCount, Action onDelayFinish)
{
return QFramework.DelayFrame.Allocate(frameCount, onDelayFinish);
}
public static IAction NextFrame(Action onNextFrame)
{
return QFramework.DelayFrame.Allocate(1, onNextFrame);
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("条件")]
[APIDescriptionEN("condition action")]
[APIExampleCode(@"
ActionKit.Sequence()
.Callback(() => Debug.Log(""Before Condition""))
.Condition(() => Input.GetMouseButtonDown(0))
.Callback(() => Debug.Log(""Mouse Clicked""))
.Start(this);
// Before Condition
// ---- after left mouse click ----
// ---- 鼠标左键点击之后 ----
// Mouse Clicked
")]
#endif
void ConditionAPI()
{
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("重复动作")]
[APIDescriptionEN("repeat action")]
[APIExampleCode(@"
ActionKit.Repeat()
.Condition(() => Input.GetMouseButtonDown(0))
.Callback(() => Debug.Log(""Mouse Clicked""))
.Start(this);
// always Log Mouse Clicked when click left mouse
// 鼠标左键点击时,每次都会输出 Mouse Clicked
ActionKit.Repeat(5) // -1、0 means forever 1 means once 2 means twice
.Condition(() => Input.GetMouseButtonDown(1))
.Callback(() => Debug.Log(""Mouse right clicked""))
.Start(this, () =>
{
Debug.Log(""Right click finished"");
});
// Mouse right clicked
// Mouse right clicked
// Mouse right clicked
// Mouse right clicked
// Mouse right clicked
// Right click finished
")]
#endif
public static IRepeat Repeat(int repeatCount = -1)
{
return QFramework.Repeat.Allocate(repeatCount);
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("并行动作")]
[APIDescriptionEN("parallel action")]
[APIExampleCode(@"
Debug.Log(""Parallel Start:"" + Time.time);
ActionKit.Parallel()
.Delay(1.0f, () => { Debug.Log(Time.time); })
.Delay(2.0f, () => { Debug.Log(Time.time); })
.Delay(3.0f, () => { Debug.Log(Time.time); })
.Start(this, () =>
{
Debug.Log(""Parallel Finish:"" + Time.time);
});
// Parallel Start:0
// 1.01
// 2.01
// 3.02
// Parallel Finish:3.02
")]
#endif
public static IParallel Parallel()
{
return QFramework.Parallel.Allocate();
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("复合动作示例")]
[APIDescriptionEN("Complex action example")]
[APIExampleCode(@"
ActionKit.Sequence()
.Callback(() => Debug.Log(""Sequence Start""))
.Callback(() => Debug.Log(""Parallel Start""))
.Parallel(p =>
{
p.Delay(1.0f, () => Debug.Log(""Delay 1s Finished""))
.Delay(2.0f, () => Debug.Log(""Delay 2s Finished""));
})
.Callback(() => Debug.Log(""Parallel Finished""))
.Callback(() => Debug.Log(""Check Mouse Clicked""))
.Sequence(s =>
{
s.Condition(() => Input.GetMouseButton(0))
.Callback(() => Debug.Log(""Mouse Clicked""));
})
.Start(this, () =>
{
Debug.Log(""Finish"");
});
//
// Sequence Start
// Parallel Start
// Delay 1s Finished
// Delay 2s Finished
// Parallel Finished
// Check Mouse Clicked
// ------ After Left Mouse Clicked ------
// ------ 鼠标左键点击后 ------
// Mouse Clicked
// Finish
")]
#endif
public void ComplexAPI()
{
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("自定义动作")]
[APIDescriptionEN("Custom action example")]
[APIExampleCode(@"
ActionKit.Custom(a =>
{
a
.OnStart(() => { Debug.Log(""OnStart""); })
.OnExecute(dt =>
{
Debug.Log(""OnExecute"");
a.Finish();
})
.OnFinish(() => { Debug.Log(""OnFinish""); });
}).Start(this);
// OnStart
// OnExecute
// OnFinish
class SomeData
{
public int ExecuteCount = 0;
}
ActionKit.Custom<SomeData>(a =>
{
a
.OnStart(() =>
{
a.Data = new SomeData()
{
ExecuteCount = 0
};
})
.OnExecute(dt =>
{
Debug.Log(a.Data.ExecuteCount);
a.Data.ExecuteCount++;
if (a.Data.ExecuteCount >= 5)
{
a.Finish();
}
}).OnFinish(() => { Debug.Log(""Finished""); });
}).Start(this);
// 0
// 1
// 2
// 3
// 4
// Finished
// 还支持 Sequence、Repeat、Parallel 等
// Also support sequence repeat Parallel
// ActionKit.Sequence()
// .Custom(c =>
// {
// c.OnStart(() => c.Finish());
// }).Start(this);
")]
#endif
public static IAction Custom(Action<ICustomAPI<object>> customSetting)
{
var action = QFramework.Custom.Allocate();
customSetting(action);
return action;
}
public static IAction Custom<TData>(Action<ICustomAPI<TData>> customSetting)
{
var action = QFramework.Custom<TData>.Allocate();
customSetting(action);
return action;
}
#if UNITY_EDITOR
[MethodAPI]
[APIDescriptionCN("协程支持")]
[APIDescriptionEN("coroutine action example")]
[APIExampleCode(@"
IEnumerator SomeCoroutine()
{
yield return new WaitForSeconds(1.0f);
Debug.Log(""Hello:"" + Time.time);
}
ActionKit.Coroutine(SomeCoroutine).Start(this);
// Hello:1.0039
SomeCoroutine().ToAction().Start(this);
// Hello:1.0039
ActionKit.Sequence()
.Coroutine(SomeCoroutine)
.Start(this);
// Hello:1.0039
")]
#endif
public static IAction Coroutine(Func<IEnumerator> coroutineGetter)
{
return CoroutineAction.Allocate(coroutineGetter);
}
#region Events
public static EasyEvent OnUpdate => ActionKitMonoBehaviourEvents.Instance.OnUpdate;
public static EasyEvent OnFixedUpdate => ActionKitMonoBehaviourEvents.Instance.OnFixedUpdate;
public static EasyEvent OnLateUpdate => ActionKitMonoBehaviourEvents.Instance.OnLateUpdate;
public static EasyEvent OnGUI => ActionKitMonoBehaviourEvents.Instance.OnGUIEvent;
public static EasyEvent OnApplicationQuit => ActionKitMonoBehaviourEvents.Instance.OnApplicationQuitEvent;
protected override void Init()
{
}
#endregion
}
}
namespace QFramework
{
public class DeprecateActionKit
{
[RuntimeInitializeOnLoadMethod]
private static void InitNodeSystem()
{
// cache list
// cache node
SafeObjectPool<DelayAction>.Instance.Init(50, 50);
SafeObjectPool<EventAction>.Instance.Init(50, 50);
}
}
/// <inheritdoc />
/// <summary>
/// 延时执行节点
/// </summary>
[Serializable]
[ActionGroup("ActionKit")]
public class DelayAction : ActionKitAction, IPoolable, IResetable
{
[SerializeField] public float DelayTime;
public System.Action OnDelayFinish { get; set; }
public float CurrentSeconds { get; set; }
public static DelayAction Allocate(float delayTime, System.Action onDelayFinish = null)
{
var retNode = SafeObjectPool<DelayAction>.Instance.Allocate();
retNode.DelayTime = delayTime;
retNode.OnDelayFinish = onDelayFinish;
retNode.CurrentSeconds = 0.0f;
return retNode;
}
protected override void OnReset()
{
CurrentSeconds = 0.0f;
}
protected override void OnExecute(float dt)
{
CurrentSeconds += dt;
Finished = CurrentSeconds >= DelayTime;
if (Finished && OnDelayFinish != null)
{
OnDelayFinish();
}
}
protected override void OnDispose()
{
SafeObjectPool<DelayAction>.Instance.Recycle(this);
}
public void OnRecycled()
{
OnDelayFinish = null;
DelayTime = 0.0f;
Reset();
}
public bool IsRecycled { get; set; }
}
public static class DelayActionExtensions
{
public static IDeprecateAction Delay<T>(this T selfBehaviour, float seconds, System.Action delayEvent)
where T : MonoBehaviour
{
var delayAction = DelayAction.Allocate(seconds, delayEvent);
selfBehaviour.ExecuteNode(delayAction);
return delayAction;
}
public static IActionChain Delay(this IActionChain selfChain, float seconds)
{
return selfChain.Append(DelayAction.Allocate(seconds));
}
}
/// <inheritdoc />
/// <summary>
/// 安枕执行节点
/// </summary>
[Serializable]
[ActionGroup("ActionKit")]
public class DelayFrameAction : ActionKitAction, IPoolable, IResetable
{
[SerializeField] public int FrameCount;
public System.Action OnDelayFrameFinish { get; set; }
public float CurrentSeconds { get; set; }
public static DelayFrameAction Allocate(int frameCount, System.Action onDelayFrameFinish = null)
{
var retNode = SafeObjectPool<DelayFrameAction>.Instance.Allocate();
retNode.FrameCount = frameCount;
retNode.OnDelayFrameFinish = onDelayFrameFinish;
retNode.CurrentSeconds = 0.0f;
return retNode;
}
protected override void OnReset()
{
CurrentSeconds = 0.0f;
}
private int StartFrame;
protected override void OnBegin()
{
base.OnBegin();
StartFrame = Time.frameCount;
}
protected override void OnExecute(float dt)
{
Finished = Time.frameCount - StartFrame >= FrameCount;
if (Finished && OnDelayFrameFinish != null)
{
OnDelayFrameFinish();
}
}
protected override void OnDispose()
{
SafeObjectPool<DelayFrameAction>.Instance.Recycle(this);
}
public void OnRecycled()
{
OnDelayFrameFinish = null;
FrameCount = 0;
Reset();
}
public bool IsRecycled { get; set; }
}
public static class DelayFrameActionExtensions
{
public static void DelayFrame<T>(this T selfBehaviour, int frameCount, System.Action delayFrameEvent)
where T : MonoBehaviour
{
selfBehaviour.ExecuteNode(DelayFrameAction.Allocate(frameCount, delayFrameEvent));
}
public static void NextFrame<T>(this T selfBehaviour, System.Action nextFrameEvent)
where T : MonoBehaviour
{
selfBehaviour.ExecuteNode(DelayFrameAction.Allocate(1, nextFrameEvent));
}
public static IActionChain DelayFrame(this IActionChain selfChain, int frameCount)
{
return selfChain.Append(DelayFrameAction.Allocate(frameCount));
}
public static IActionChain NextFrame(this IActionChain selfChain)
{
return selfChain.Append(DelayFrameAction.Allocate(1));
}
}
/// <inheritdoc />
/// <summary>
/// 延时执行节点
/// </summary>
[OnlyUsedByCode]
public class EventAction : ActionKitAction, IPoolable
{
private System.Action mOnExecuteEvent;
/// <summary>
/// TODO:这里填可变参数会有问题
/// </summary>
/// <param name="onExecuteEvents"></param>
/// <returns></returns>
public static EventAction Allocate(params System.Action[] onExecuteEvents)
{
var retNode = SafeObjectPool<EventAction>.Instance.Allocate();
Array.ForEach(onExecuteEvents, onExecuteEvent => retNode.mOnExecuteEvent += onExecuteEvent);
return retNode;
}
/// <summary>
/// finished
/// </summary>
protected override void OnExecute(float dt)
{
if (mOnExecuteEvent != null)
{
mOnExecuteEvent.Invoke();
}
Finished = true;
}
protected override void OnDispose()
{
SafeObjectPool<EventAction>.Instance.Recycle(this);
}
public void OnRecycled()
{
Reset();
mOnExecuteEvent = null;
}
public bool IsRecycled { get; set; }
}
[OnlyUsedByCode]
public class OnlyBeginAction : ActionKitAction, IPoolable, IPoolType
{
private Action<OnlyBeginAction> mBeginAction;
public static OnlyBeginAction Allocate(Action<OnlyBeginAction> beginAction)
{
var retSimpleAction = SafeObjectPool<OnlyBeginAction>.Instance.Allocate();
retSimpleAction.mBeginAction = beginAction;
return retSimpleAction;
}
public void OnRecycled()
{
mBeginAction = null;
}
protected override void OnBegin()
{
if (mBeginAction != null)
{
mBeginAction.Invoke(this);
}
}
public bool IsRecycled { get; set; }
public void Recycle2Cache()
{
SafeObjectPool<OnlyBeginAction>.Instance.Recycle(this);
}
}
/// <inheritdoc />
/// <summary>
/// like filter, add condition
/// </summary>
[OnlyUsedByCode]
public class UntilAction : ActionKitAction, IPoolable
{
private Func<bool> mCondition;
public static UntilAction Allocate(Func<bool> condition)
{
var retNode = SafeObjectPool<UntilAction>.Instance.Allocate();
retNode.mCondition = condition;
return retNode;
}
protected override void OnExecute(float dt)
{
Finished = mCondition.Invoke();
}
protected override void OnDispose()
{
SafeObjectPool<UntilAction>.Instance.Recycle(this);
}
void IPoolable.OnRecycled()
{
Reset();
mCondition = null;
}
bool IPoolable.IsRecycled { get; set; }
}
internal class OnDestroyDisposeTrigger : MonoBehaviour
{
HashSet<IDisposable> mDisposables = new HashSet<IDisposable>();
public void AddDispose(IDisposable disposable)
{
if (!mDisposables.Contains(disposable))
{
mDisposables.Add(disposable);
}
}
private void OnDestroy()
{
if (Application.isPlaying)
{
foreach (var disposable in mDisposables)
{
disposable.Dispose();
}
mDisposables.Clear();
mDisposables = null;
}
}
}
internal class OnDisableDisposeTrigger : MonoBehaviour
{
HashSet<IDisposable> mDisposables = new HashSet<IDisposable>();
public void AddDispose(IDisposable disposable)
{
if (!mDisposables.Contains(disposable))
{
mDisposables.Add(disposable);
}
}
private void OnDisable()
{
if (Application.isPlaying)
{
foreach (var disposable in mDisposables)
{
disposable.Dispose();
}
mDisposables.Clear();
mDisposables = null;
}
}
}
internal static class IDisposableExtensions
{
/// <summary>
/// 与 GameObject 绑定销毁
/// </summary>
/// <param name="self"></param>
/// <param name="component"></param>
public static void DisposeWhenGameObjectDestroyed(this IDisposable self, Component component)
{
var onDestroyDisposeTrigger = component.gameObject.GetComponent<OnDestroyDisposeTrigger>();
if (!onDestroyDisposeTrigger)
{
onDestroyDisposeTrigger = component.gameObject.AddComponent<OnDestroyDisposeTrigger>();
}
onDestroyDisposeTrigger.AddDispose(self);
}
}
/// <summary>
/// 时间轴执行节点
/// </summary>
public class Timeline : ActionKitAction
{
private float mCurTime = 0;
public System.Action OnTimelineBeganCallback
{
get { return OnBeganCallback; }
set { OnBeganCallback = value; }
}
public System.Action OnTimelineEndedCallback
{
get { return OnEndedCallback; }
set { OnEndedCallback = value; }
}
public Action<string> OnKeyEventsReceivedCallback = null;
public class TimelinePair
{
public float Time;
public IDeprecateAction Node;
public TimelinePair(float time, IDeprecateAction node)
{
Time = time;
Node = node;
}
}
/// <summary>
/// refator 2 one list? all in one list;
/// </summary>
public Queue<TimelinePair> TimelineQueue = new Queue<TimelinePair>();
protected override void OnReset()
{
mCurTime = 0.0f;
foreach (var timelinePair in TimelineQueue)
{
timelinePair.Node.Reset();
}
}
protected override void OnExecute(float dt)
{
mCurTime += dt;
foreach (var pair in TimelineQueue.Where(pair => pair.Time < mCurTime && !pair.Node.Finished))
{
if (pair.Node.Execute(dt))
{
Finished = TimelineQueue.Count(timelinePair => !timelinePair.Node.Finished) == 0;
}
}
}
public Timeline(params TimelinePair[] pairs)
{
foreach (var pair in pairs)
{
TimelineQueue.Enqueue(pair);
}
}
public void Append(TimelinePair pair)
{
TimelineQueue.Enqueue(pair);
}
public void Append(float time, IDeprecateAction node)
{
TimelineQueue.Enqueue(new TimelinePair(time, node));
}
protected override void OnDispose()
{
foreach (var timelinePair in TimelineQueue)
{
timelinePair.Node.Dispose();
}
TimelineQueue.Clear();
TimelineQueue = null;
}
}
public class KeyEventAction : ActionKitAction, IPoolable
{
private Timeline mTimeline;
private string mEventName;
public static KeyEventAction Allocate(string eventName, Timeline timeline)
{
var keyEventAction = SafeObjectPool<KeyEventAction>.Instance.Allocate();
keyEventAction.mEventName = eventName;
keyEventAction.mTimeline = timeline;
return keyEventAction;
}
protected override void OnBegin()
{
base.OnBegin();
mTimeline.OnKeyEventsReceivedCallback?.Invoke(mEventName);
Finish();
}
protected override void OnDispose()
{
SafeObjectPool<KeyEventAction>.Instance.Recycle(this);
}
public void OnRecycled()
{
mTimeline = null;
mEventName = null;
}
public bool IsRecycled { get; set; }
}
public class AsyncNode : ActionKitAction
{
public HashSet<IDeprecateAction> mActions = new HashSet<IDeprecateAction>();
public void Add(IDeprecateAction action)
{
mActions.Add(action);
}
protected override void OnExecute(float dt)
{
foreach (var action in mActions.Where(action => action.Execute(dt)))
{
mActions.Remove(action);
action.Dispose();
}
}
}
public class QueueNode : ActionKitAction
{
private Queue<IDeprecateAction> mQueue = new Queue<IDeprecateAction>(20);
public void Enqueue(IDeprecateAction action)
{
mQueue.Enqueue(action);
}
protected override void OnExecute(float dt)
{
if (mQueue.Count != 0 && mQueue.Peek().Execute(dt))
{
mQueue.Dequeue().Dispose();
}
}
}
public interface IResetable
{
void Reset();
}
[OnlyUsedByCode]
public class RepeatNode : ActionKitAction, INode
{
public RepeatNode(IDeprecateAction node, int repeatCount = -1)
{
RepeatCount = repeatCount;
mNode = node;
}
public IDeprecateAction CurrentExecutingNode
{
get
{
var currentNode = mNode;
var node = currentNode as INode;
return node == null ? currentNode : node.CurrentExecutingNode;
}
}
private IDeprecateAction mNode;
public int RepeatCount = 1;
private int mCurRepeatCount = 0;
protected override void OnReset()
{
if (null != mNode)
{
mNode.Reset();
}
mCurRepeatCount = 0;
Finished = false;
}
protected override void OnExecute(float dt)
{
if (RepeatCount == -1)
{
if (mNode.Execute(dt))
{
mNode.Reset();
}
return;
}
if (mNode.Execute(dt))
{
mNode.Reset();
mCurRepeatCount++;
}
if (mCurRepeatCount == RepeatCount)
{
Finished = true;
}
}
protected override void OnDispose()
{
if (null != mNode)
{
mNode.Dispose();
mNode = null;
}
}
}
/// <summary>
/// 序列执行节点
/// </summary>
[OnlyUsedByCode]
public class SequenceNode : ActionKitAction, INode, IResetable
{
protected List<IDeprecateAction> mNodes = ListPool<IDeprecateAction>.Get();
protected List<IDeprecateAction> mExcutingNodes = ListPool<IDeprecateAction>.Get();
public int TotalCount
{
get { return mExcutingNodes.Count; }
}
public IDeprecateAction CurrentExecutingNode
{
get
{
var currentNode = mExcutingNodes[0];
var node = currentNode as INode;
return node == null ? currentNode : node.CurrentExecutingNode;
}
}
protected override void OnReset()
{
mExcutingNodes.Clear();
foreach (var node in mNodes)
{
node.Reset();
mExcutingNodes.Add(node);
}
}
protected override void OnExecute(float dt)
{
if (mExcutingNodes.Count > 0)
{
// 如果有异常,则进行销毁,不再进行下边的操作
if (mExcutingNodes[0].Disposed && !mExcutingNodes[0].Finished)
{
Dispose();
return;
}
while (mExcutingNodes[0].Execute(dt))
{
mExcutingNodes.RemoveAt(0);
OnCurrentActionFinished();
if (mExcutingNodes.Count == 0)
{
break;
}
}
}
Finished = mExcutingNodes.Count == 0;
}
protected virtual void OnCurrentActionFinished()
{
}
public SequenceNode(params IDeprecateAction[] nodes)
{
foreach (var node in nodes)
{
mNodes.Add(node);
mExcutingNodes.Add(node);
}
}
public SequenceNode Append(IDeprecateAction appendedNode)
{
mNodes.Add(appendedNode);
mExcutingNodes.Add(appendedNode);
return this;
}
protected override void OnDispose()
{
base.OnDispose();
if (null != mNodes)
{
mNodes.ForEach(node => node.Dispose());
mNodes.Clear();
mNodes.Release2Pool();
mNodes = null;
}
if (null != mExcutingNodes)
{
mExcutingNodes.Release2Pool();
mExcutingNodes = null;
}
}
}
/// <summary>
/// 并发执行的协程
/// </summary>
[OnlyUsedByCode]
public class SpawnNode : ActionKitAction
{
protected List<ActionKitAction> mNodes = ListPool<ActionKitAction>.Get();
protected override void OnReset()
{
mNodes.ForEach(node => node.Reset());
mFinishCount = 0;
}
public override void Finish()
{
for (var i = mNodes.Count - 1; i >= 0; i--)
{
mNodes[i].Finish();
}
base.Finish();
}
protected override void OnExecute(float dt)
{
for (var i = mNodes.Count - 1; i >= 0; i--)
{
var node = mNodes[i];
if (!node.Finished && node.Execute(dt))
Finished = mNodes.Count == mFinishCount;
}
}
private int mFinishCount = 0;
private void IncreaseFinishCount()
{
mFinishCount++;
}
public SpawnNode(params ActionKitAction[] nodes)
{
mNodes.AddRange(nodes);
foreach (var nodeAction in nodes)
{
nodeAction.OnEndedCallback += IncreaseFinishCount;
}
}
public void Add(params ActionKitAction[] nodes)
{
mNodes.AddRange(nodes);
foreach (var nodeAction in nodes)
{
nodeAction.OnEndedCallback += IncreaseFinishCount;
}
}
protected override void OnDispose()
{
foreach (var node in mNodes)
{
node.OnEndedCallback -= IncreaseFinishCount;
node.Dispose();
}
mNodes.Release2Pool();
mNodes = null;
}
}
public class ActionKitFSM
{
public ActionKitFSMState CurrentState { get; private set; }
public Type PreviousStateType { get; private set; }
public void Update()
{
if (CurrentState != null)
{
CurrentState.Update();
}
}
public void FixedUpdate()
{
if (CurrentState != null)
{
CurrentState.FixedUpdate();
}
}
private Dictionary<Type, ActionKitFSMState> mStates = new Dictionary<Type, ActionKitFSMState>();
private ActionKitFSMTransitionTable mTrasitionTable = new ActionKitFSMTransitionTable();
public void AddState(ActionKitFSMState state)
{
mStates.Add(state.GetType(), state);
}
public void AddTransition(ActionKitFSMTransition transition)
{
mTrasitionTable.Add(transition);
}
public bool HandleEvent<TTransition>() where TTransition : ActionKitFSMTransition
{
foreach (var transition in mTrasitionTable.TypeIndex.Get(typeof(TTransition)))
{
if (transition.SrcStateTypes.Contains(CurrentState.GetType()))
{
var currentState = CurrentState;
var nextState = mStates[transition.DstStateType];
CurrentState.Exit();
transition.OnTransition(currentState, nextState);
CurrentState = nextState;
CurrentState.Enter();
return true;
}
}
return false;
}
public void ChangeState<TState>() where TState : ActionKitFSMState
{
ChangeState(typeof(TState));
}
public void ChangeState(Type stateType)
{
if (CurrentState.GetType() != stateType)
{
PreviousStateType = CurrentState.GetType();
CurrentState.Exit();
CurrentState = mStates[stateType];
CurrentState.Enter();
}
}
public void BackToPreviousState()
{
ChangeState(PreviousStateType);
}
public void StartState<T>()
{
CurrentState = mStates[typeof(T)];
CurrentState.Enter();
}
}
public class ActionKitFSMState
{
public void Enter()
{
OnEnter();
}
public void Update()
{
OnUpdate();
}
public void FixedUpdate()
{
OnFixedUpdate();
}
public void Exit()
{
OnExit();
}
protected virtual void OnEnter()
{
}
protected virtual void OnUpdate()
{
}
protected virtual void OnFixedUpdate()
{
}
protected virtual void OnExit()
{
}
}
public class ActionKitFSMState<T> : ActionKitFSMState
{
public ActionKitFSMState(T target)
{
mTarget = target;
}
protected T mTarget;
public T Target
{
get { return mTarget; }
}
}
public class ActionKitFSMTransition
{
public virtual HashSet<Type> SrcStateTypes { get; set; }
public virtual Type DstStateType { get; set; }
public virtual void OnTransition(ActionKitFSMState srcState, ActionKitFSMState dstState)
{
}
public ActionKitFSMTransition AddSrcState<T>() where T : ActionKitFSMState
{
if (SrcStateTypes == null)
{
SrcStateTypes = new HashSet<Type>()
{
typeof(T)
};
}
else
{
SrcStateTypes.Add(typeof(T));
}
return this;
}
public ActionKitFSMTransition WithDstState<T>() where T : ActionKitFSMState
{
DstStateType = typeof(T);
return this;
}
}
public class ActionKitFSMTransition<TSrcState, TDstState> : ActionKitFSMTransition
{
private Type mSrcStateType = typeof(TSrcState);
private Type mDstStateType = typeof(TDstState);
public override HashSet<Type> SrcStateTypes
{
get { return new HashSet<Type>() { mSrcStateType }; }
}
public override Type DstStateType
{
get { return mDstStateType; }
}
}
public struct EnumStateChangeEvent<T> where T : struct, IComparable, IConvertible, IFormattable
{
public GameObject Target;
public EnumStateMachine<T> TargetStateMachine;
public T NewState;
public T PreviousState;
public EnumStateChangeEvent(EnumStateMachine<T> stateMachine)
{
Target = stateMachine.Target;
TargetStateMachine = stateMachine;
NewState = stateMachine.CurrentState;
PreviousState = stateMachine.PreviousState;
}
}
public interface IEnumStateMachine
{
bool TriggerEvents { get; set; }
}
public class EnumStateMachine<T> : IEnumStateMachine where T : struct, IComparable, IConvertible, IFormattable
{
/// If you set TriggerEvents to true, the state machine will trigger events when entering and exiting a state.
/// Additionnally, if you also use a StateMachineProcessor, it'll trigger events for the current state on FixedUpdate, LateUpdate, but also
/// on Update (separated in EarlyUpdate, Update and EndOfUpdate, triggered in this order at Update()
/// To listen to these events, from any class, in its Start() method (or wherever you prefer), use MMEventManager.StartListening(gameObject.GetInstanceID().ToString()+"XXXEnter",OnXXXEnter);
/// where XXX is the name of the state you're listening to, and OnXXXEnter is the method you want to call when that event is triggered.
/// MMEventManager.StartListening(gameObject.GetInstanceID().ToString()+"CrouchingEarlyUpdate",OnCrouchingEarlyUpdate); for example will listen to the Early Update event of the Crouching state, and
/// will trigger the OnCrouchingEarlyUpdate() method.
public bool TriggerEvents { get; set; }
/// the name of the target gameobject
public GameObject Target;
/// the current character's movement state
public T CurrentState { get; protected set; }
/// the character's movement state before entering the current one
public T PreviousState { get; protected set; }
/// <summary>
/// Creates a new StateMachine, with a targetName (used for events, usually use GetInstanceID()), and whether you want to use events with it or not
/// </summary>
/// <param name="targetName">Target name.</param>
/// <param name="triggerEvents">If set to <c>true</c> trigger events.</param>
public EnumStateMachine(GameObject target, bool triggerEvents)
{
this.Target = target;
this.TriggerEvents = triggerEvents;
}
/// <summary>
/// 切换状态
/// </summary>
/// <param name="newState">New state.</param>
public virtual void ChangeState(T newState)
{
// if the "new state" is the current one, we do nothing and exit
if (newState.Equals(CurrentState))
{
return;
}
// we store our previous character movement state
PreviousState = CurrentState;
CurrentState = newState;
if (TriggerEvents)
{
TypeEventSystem.Global.Send(new EnumStateChangeEvent<T>(this));
}
}
/// <summary>
/// 返回上一个状态
/// </summary>
public virtual void RestorePreviousState()
{
CurrentState = PreviousState;
if (TriggerEvents)
{
TypeEventSystem.Global.Send(new EnumStateChangeEvent<T>(this));
}
}
}
public class ActionKitFSMTransitionTable : Table<ActionKitFSMTransition>
{
public TableIndex<Type, ActionKitFSMTransition> TypeIndex =
new TableIndex<Type, ActionKitFSMTransition>(t => t.GetType());
protected override void OnAdd(ActionKitFSMTransition item)
{
TypeIndex.Add(item);
}
protected override void OnRemove(ActionKitFSMTransition item)
{
TypeIndex.Remove(item);
}
protected override void OnClear()
{
TypeIndex.Clear();
}
public override IEnumerator<ActionKitFSMTransition> GetEnumerator()
{
return TypeIndex.Dictionary.SelectMany(src => src.Value).GetEnumerator();
}
protected override void OnDispose()
{
TypeIndex.Dispose();
}
}
/// <summary>
/// FSM 基于枚举的状态机
/// </summary>
public class FSM<TStateEnum, TEventEnum> : IDisposable
{
private Action<TStateEnum, TStateEnum> mOnStateChanged = null;
public FSM(Action<TStateEnum, TStateEnum> onStateChanged = null)
{
mOnStateChanged = onStateChanged;
}
/// <summary>
/// FSM onStateChagned.
/// </summary>
public delegate void FSMOnStateChanged(params object[] param);
/// <summary>
/// QFSM state.
/// </summary>
public class FSMState<TName>
{
public TName Name;
public FSMState(TName name)
{
Name = name;
}
/// <summary>
/// The translation dict.
/// </summary>
public readonly Dictionary<TEventEnum, FSMTranslation<TName, TEventEnum>> TranslationDict =
new Dictionary<TEventEnum, FSMTranslation<TName, TEventEnum>>();
}
/// <summary>
/// Translation
/// </summary>
public class FSMTranslation<TStateName, KEventName>
{
public TStateName FromState;
public KEventName Name;
public TStateName ToState;
public Action<object[]> OnTranslationCallback; // 回调函数
public FSMTranslation(TStateName fromState, KEventName name, TStateName toState,
Action<object[]> onStateChagned)
{
FromState = fromState;
ToState = toState;
Name = name;
OnTranslationCallback = onStateChagned;
}
}
/// <summary>
/// The state of the m current.
/// </summary>
TStateEnum mCurState;
public TStateEnum State
{
get { return mCurState; }
}
/// <summary>
/// The m state dict.
/// </summary>
Dictionary<TStateEnum, FSMState<TStateEnum>>
mStateDict = new Dictionary<TStateEnum, FSMState<TStateEnum>>();
/// <summary>
/// Adds the state.
/// </summary>
/// <param name="name">Name.</param>
private void AddState(TStateEnum name)
{
mStateDict[name] = new FSMState<TStateEnum>(name);
}
/// <summary>
/// Adds the translation.
/// </summary>
/// <param name="fromState">From state.</param>
/// <param name="name">Name.</param>
/// <param name="toState">To state.</param>
/// <param name="onStateChagned">Callfunc.</param>
public void AddTransition(TStateEnum fromState, TEventEnum name, TStateEnum toState,
Action<object[]> onStateChagned = null)
{
if (!mStateDict.ContainsKey(fromState))
{
AddState(fromState);
}
if (!mStateDict.ContainsKey(toState))
{
AddState(toState);
}
mStateDict[fromState].TranslationDict[name] =
new FSMTranslation<TStateEnum, TEventEnum>(fromState, name, toState, onStateChagned);
}
/// <summary>
/// Start the specified name.
/// </summary>
/// <param name="name">Name.</param>
public void Start(TStateEnum name)
{
mCurState = name;
}
/// <summary>
/// Handles the event.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="param">Parameter.</param>
public void HandleEvent(TEventEnum name, params object[] param)
{
if (mCurState != null && mStateDict[mCurState].TranslationDict.ContainsKey(name))
{
var tempTranslation = mStateDict[mCurState].TranslationDict[name];
if (tempTranslation.OnTranslationCallback != null)
{
tempTranslation.OnTranslationCallback.Invoke(param);
}
if (mOnStateChanged != null)
{
mOnStateChanged.Invoke(mCurState, tempTranslation.ToState);
}
mCurState = tempTranslation.ToState;
}
}
/// <summary>
/// Clear this instance.
/// </summary>
public void Clear()
{
foreach (var keyValuePair in mStateDict)
{
foreach (var translationDictValue in keyValuePair.Value.TranslationDict.Values)
{
translationDictValue.OnTranslationCallback = null;
}
keyValuePair.Value.TranslationDict.Clear();
}
mStateDict.Clear();
}
public void Dispose()
{
Clear();
}
}
/// <summary>
/// QFSM lite.
/// 基于字符串的状态机
/// </summary>
public class QFSMLite
{
/// <summary>
/// FSM callfunc.
/// </summary>
public delegate void FSMCallfunc(params object[] param);
/// <summary>
/// QFSM state.
/// </summary>
class QFSMState
{
public string Name;
public QFSMState(string name)
{
Name = name;
}
/// <summary>
/// The translation dict.
/// </summary>
public readonly Dictionary<string, QFSMTranslation> TranslationDict =
new Dictionary<string, QFSMTranslation>();
}
/// <summary>
/// Translation
/// </summary>
public class QFSMTranslation
{
public string FromState;
public string Name;
public string ToState;
public FSMCallfunc OnTranslationCallback; // 回调函数
public QFSMTranslation(string fromState, string name, string toState, FSMCallfunc onTranslationCallback)
{
FromState = fromState;
ToState = toState;
Name = name;
OnTranslationCallback = onTranslationCallback;
}
}
/// <summary>
/// The state of the m current.
/// </summary>
string mCurState;
public string State
{
get { return mCurState; }
}
/// <summary>
/// The m state dict.
/// </summary>
Dictionary<string, QFSMState> mStateDict = new Dictionary<string, QFSMState>();
/// <summary>
/// Adds the state.
/// </summary>
/// <param name="name">Name.</param>
public void AddState(string name)
{
mStateDict[name] = new QFSMState(name);
}
/// <summary>
/// Adds the translation.
/// </summary>
/// <param name="fromState">From state.</param>
/// <param name="name">Name.</param>
/// <param name="toState">To state.</param>
/// <param name="callfunc">Callfunc.</param>
public void AddTranslation(string fromState, string name, string toState, FSMCallfunc callfunc)
{
mStateDict[fromState].TranslationDict[name] = new QFSMTranslation(fromState, name, toState, callfunc);
}
/// <summary>
/// Start the specified name.
/// </summary>
/// <param name="name">Name.</param>
public void Start(string name)
{
mCurState = name;
}
/// <summary>
/// Handles the event.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="param">Parameter.</param>
public void HandleEvent(string name, params object[] param)
{
if (mCurState != null && mStateDict[mCurState].TranslationDict.ContainsKey(name))
{
var tempTranslation = mStateDict[mCurState].TranslationDict[name];
tempTranslation.OnTranslationCallback(param);
mCurState = tempTranslation.ToState;
}
}
/// <summary>
/// Clear this instance.
/// </summary>
public void Clear()
{
mStateDict.Clear();
}
}
public interface IDeprecateAction : IDisposable
{
bool Disposed { get; }
bool Execute(float delta);
void Reset();
void Finish();
bool Finished { get; }
}
[System.Serializable]
public class ActionData
{
[SerializeField] public string ActionName;
[SerializeField] public string AcitonData;
}
public interface INode
{
IDeprecateAction CurrentExecutingNode { get; }
}
[Serializable]
public abstract class ActionKitAction : IDeprecateAction
{
public System.Action OnBeganCallback = null;
public System.Action OnEndedCallback = null;
public System.Action OnDisposedCallback = null;
protected bool mOnBeginCalled = false;
#region IAction Support
bool IDeprecateAction.Disposed
{
get { return mDisposed; }
}
protected bool mDisposed = false;
public bool Finished { get; protected set; }
public virtual void Finish()
{
Finished = true;
}
public void Break()
{
Finished = true;
}
#endregion
#region ResetableSupport
public void Reset()
{
Finished = false;
mOnBeginCalled = false;
mDisposed = false;
OnReset();
}
#endregion
#region IExecutable Support
public bool Execute(float dt)
{
if (mDisposed) return true;
// 有可能被别的地方调用
if (Finished)
{
return Finished;
}
if (!mOnBeginCalled)
{
mOnBeginCalled = true;
OnBegin();
if (OnBeganCallback != null)
{
OnBeganCallback.Invoke();
}
}
if (!Finished)
{
OnExecute(dt);
}
if (Finished)
{
if (OnEndedCallback != null)
{
OnEndedCallback.Invoke();
}
OnEnd();
}
return Finished || mDisposed;
}
#endregion
protected virtual void OnReset()
{
}
protected virtual void OnBegin()
{
}
/// <summary>
/// finished
/// </summary>
protected virtual void OnExecute(float dt)
{
}
protected virtual void OnEnd()
{
}
protected virtual void OnDispose()
{
}
#region IDisposable Support
public void Dispose()
{
if (mDisposed) return;
mDisposed = true;
OnBeganCallback = null;
OnEndedCallback = null;
if (OnDisposedCallback != null)
{
OnDisposedCallback.Invoke();
}
OnDisposedCallback = null;
OnDispose();
}
#endregion
}
public class OnlyUsedByCodeAttribute : Attribute
{
}
public class ActionGroupAttribute : Attribute
{
public readonly string GroupName;
public ActionGroupAttribute(string groupName)
{
GroupName = groupName;
}
}
/// <summary>
/// 支持链式方法
/// </summary>
public class SequenceNodeChain : ActionChain
{
protected override ActionKitAction mNode
{
get { return mSequenceNode; }
}
private SequenceNode mSequenceNode;
public SequenceNodeChain()
{
mSequenceNode = new SequenceNode();
}
public override IActionChain Append(IDeprecateAction node)
{
mSequenceNode.Append(node);
return this;
}
protected override void OnDispose()
{
base.OnDispose();
mSequenceNode.Dispose();
mSequenceNode = null;
}
}
public class RepeatNodeChain : ActionChain
{
protected override ActionKitAction mNode
{
get { return mRepeatNodeAction; }
}
private RepeatNode mRepeatNodeAction;
private SequenceNode mSequenceNode;
public RepeatNodeChain(int repeatCount)
{
mSequenceNode = new SequenceNode();
mRepeatNodeAction = new RepeatNode(mSequenceNode, repeatCount);
}
public override IActionChain Append(IDeprecateAction node)
{
mSequenceNode.Append(node);
return this;
}
protected override void OnDispose()
{
base.OnDispose();
if (null != mRepeatNodeAction)
{
mRepeatNodeAction.Dispose();
}
mRepeatNodeAction = null;
mSequenceNode.Dispose();
mSequenceNode = null;
}
}
public interface IDisposeWhen : IDisposeEventRegister
{
IDisposeEventRegister DisposeWhen(Func<bool> condition);
}
public interface IDisposeEventRegister
{
void OnDisposed(System.Action onDisposedEvent);
IDisposeEventRegister OnFinished(System.Action onFinishedEvent);
}
public static class IActionExtension
{
public static T ExecuteNode<T>(this T selBehaviour, IDeprecateAction commandNode) where T : MonoBehaviour
{
selBehaviour.StartCoroutine(commandNode.Execute());
return selBehaviour;
}
private static WaitForEndOfFrame mEndOfFrame = new WaitForEndOfFrame();
public static IEnumerator Execute(this IDeprecateAction selfNode)
{
if (selfNode.Finished) selfNode.Reset();
while (!selfNode.Execute(Time.deltaTime))
{
yield return mEndOfFrame;
}
}
}
public static partial class IActionChainExtention
{
public static IActionChain Repeat<T>(this T selfbehaviour, int count = -1) where T : MonoBehaviour
{
var retNodeChain = new RepeatNodeChain(count) { Executer = selfbehaviour };
retNodeChain.DisposeWhenGameObjectDestroyed(selfbehaviour);
return retNodeChain;
}
public static IActionChain Sequence<T>(this T selfbehaviour) where T : MonoBehaviour
{
var retNodeChain = new SequenceNodeChain { Executer = selfbehaviour };
retNodeChain.DisposeWhenGameObjectDestroyed(selfbehaviour);
return retNodeChain;
}
public static IActionChain OnlyBegin(this IActionChain selfChain, Action<OnlyBeginAction> onBegin)
{
return selfChain.Append(OnlyBeginAction.Allocate(onBegin));
}
/// <summary>
/// Same as Delayw
/// </summary>
/// <param name="senfChain"></param>
/// <param name="seconds"></param>
/// <returns></returns>
public static IActionChain Wait(this IActionChain senfChain, float seconds)
{
return senfChain.Append(DelayAction.Allocate(seconds));
}
public static IActionChain Event(this IActionChain selfChain, params System.Action[] onEvents)
{
return selfChain.Append(EventAction.Allocate(onEvents));
}
public static IActionChain Until(this IActionChain selfChain, Func<bool> condition)
{
return selfChain.Append(UntilAction.Allocate(condition));
}
}
public interface IActionChain : IDeprecateAction
{
MonoBehaviour Executer { get; set; }
IActionChain Append(IDeprecateAction node);
IDisposeWhen Begin();
}
public abstract class ActionChain : ActionKitAction, IActionChain, IDisposeWhen
{
public MonoBehaviour Executer { get; set; }
protected abstract ActionKitAction mNode { get; }
public abstract IActionChain Append(IDeprecateAction node);
protected override void OnExecute(float dt)
{
if (mDisposeWhenCondition && mDisposeCondition != null && mDisposeCondition.Invoke())
{
Finish();
}
else
{
Finished = mNode.Execute(dt);
}
}
protected override void OnEnd()
{
base.OnEnd();
Dispose();
}
protected override void OnDispose()
{
base.OnDispose();
Executer = null;
mDisposeWhenCondition = false;
mDisposeCondition = null;
if (mOnDisposedEvent != null)
{
mOnDisposedEvent.Invoke();
}
mOnDisposedEvent = null;
}
public IDisposeWhen Begin()
{
Executer.ExecuteNode(this);
return this;
}
private bool mDisposeWhenCondition = false;
private Func<bool> mDisposeCondition;
private System.Action mOnDisposedEvent = null;
public IDisposeEventRegister DisposeWhen(Func<bool> condition)
{
mDisposeWhenCondition = true;
mDisposeCondition = condition;
return this;
}
IDisposeEventRegister IDisposeEventRegister.OnFinished(System.Action onFinishedEvent)
{
OnEndedCallback += onFinishedEvent;
return this;
}
public void OnDisposed(System.Action onDisposedEvent)
{
mOnDisposedEvent = onDisposedEvent;
}
}
/// <summary>
/// 事件注入,和 NodeSystem 配套使用
/// </summary>
/// <typeparam name="T"></typeparam>
public class EventInjector<T>
{
public delegate bool InjectEventTrigger(T lastValue, T newValue);
public delegate T InjectEventGetter();
private T mCahedLastValue;
public readonly Func<T> mGetter;
public T Value
{
get { return mCahedLastValue; }
}
public EventInjector(Func<T> getter)
{
mGetter = getter;
}
public bool GetOn(InjectEventTrigger triggerConditionWithOldAndNewValue)
{
var value = mGetter();
var trig = triggerConditionWithOldAndNewValue(mCahedLastValue, value);
mCahedLastValue = value;
return trig;
}
public bool GetOnValueChanged(Func<T, bool> triggerConditionWithNewValue = null)
{
return GetOn((lastValue, newValue) =>
lastValue.Equals(newValue) &&
(triggerConditionWithNewValue == null || triggerConditionWithNewValue(newValue)));
}
}
[MonoSingletonPath("[ActionKit]/ActionQueue")]
public class ActionQueue : MonoBehaviour, ISingleton
{
private List<IDeprecateAction> mActions = new List<IDeprecateAction>();
public static void Append(IDeprecateAction action)
{
mInstance.mActions.Add(action);
}
// Update is called once per frame
private void Update()
{
if (mActions.Count != 0 && mActions[0].Execute(Time.deltaTime))
{
mActions.RemoveAt(0);
}
}
void ISingleton.OnSingletonInit()
{
}
private static ActionQueue mInstance
{
get { return MonoSingletonProperty<ActionQueue>.Instance; }
}
}
#region ECA
public class EmptyEventData
{
public static EmptyEventData Default;
}
public interface IECAEvent<T>
{
void Register(UnityAction<T> onEvent);
void UnRegister(UnityAction<T> onEvent);
void Trigger(T t);
}
public interface IECACondition<T>
{
bool Match(T t);
}
public interface IECAAction<T>
{
void Execute(T t);
}
public interface IECARule<T> : IDisposable
{
IECAEvent<T> E { get; set; }
IECACondition<T> C { get; set; }
IECAAction<T> A { get; set; }
IECARule<T> Build();
}
public class ECARule<T> : IECARule<T>
{
public IECAEvent<T> E { get; set; }
public IECACondition<T> C { get; set; }
public IECAAction<T> A { get; set; }
void OnEvent(T t)
{
if (C.Match(t))
{
A.Execute(t);
}
}
public IECARule<T> Build()
{
E.Register(OnEvent);
return this;
}
public void Dispose()
{
E.UnRegister(OnEvent);
E = null;
C = null;
A = null;
}
}
public class CustomECACondition<T> : IECACondition<T>
{
private readonly Func<T, bool> mCondition;
public CustomECACondition(Func<T, bool> condition)
{
mCondition = condition;
}
public bool Match(T t)
{
return mCondition.Invoke(t);
}
}
public class CustomECAAction<T> : IECAAction<T>
{
private readonly UnityAction<T> mAction;
public CustomECAAction(UnityAction<T> action)
{
mAction = action;
}
public void Execute(T t)
{
mAction?.Invoke(t);
}
}
public static class ECARuleExtension
{
public static IECARule<T> Condition<T>(this IECARule<T> self, Func<T, bool> condition)
{
self.C = new CustomECACondition<T>(condition);
return self;
}
public static IECARule<T> Condition<T>(this IECARule<T> self, Func<bool> condition)
{
self.C = new CustomECACondition<T>(_ => condition());
return self;
}
public static IECARule<T> Action<T>(this IECARule<T> self, UnityAction<T> action)
{
self.A = new CustomECAAction<T>(action);
return self;
}
public static IECARule<T> Action<T>(this IECARule<T> self, UnityAction action)
{
self.A = new CustomECAAction<T>(_ => action());
return self;
}
}
public class UnityEventT<T> : UnityEvent<T>
{
}
public class MonoEventTrigger<T> : MonoBehaviour, IECAEvent<T>
{
public UnityEvent<T> Event = new UnityEventT<T>();
public void Register(UnityAction<T> onEvent)
{
Event.AddListener(onEvent);
}
public void UnRegister(UnityAction<T> onEvent)
{
Event.RemoveListener(onEvent);
}
public void Trigger(T t)
{
Event?.Invoke(t);
}
}
public class UpdateTrigger : MonoEventTrigger<EmptyEventData>
{
private void Update()
{
Trigger(EmptyEventData.Default);
}
}
public class FixedUpdateTrigger : MonoEventTrigger<EmptyEventData>
{
private void FixedUpdate()
{
Trigger(EmptyEventData.Default);
}
}
public class LateUpdateTrigger : MonoEventTrigger<EmptyEventData>
{
private void LateUpdate()
{
Trigger(EmptyEventData.Default);
}
}
public class OnTriggerEnter2DTrigger : MonoEventTrigger<Collider2D>
{
private void OnTriggerEnter2D(Collider2D col)
{
Trigger(col);
}
}
public static class ECARuleTriggerExtension
{
public static void OnUpdate(this Component self, UnityAction onUpdate)
{
self.UpdateEvent().Condition(_ => true).Action(_ => onUpdate()).Build();
}
public static void OnFixedUpdate(this Component self, UnityAction onFixedUpdate)
{
self.FixedUpdateEvent().Condition(_ => true).Action(_ => onFixedUpdate()).Build();
}
public static void OnLateUpdate(this Component self, UnityAction onLateUpdate)
{
self.LateUpdateEvent().Condition(_ => true).Action(_ => onLateUpdate()).Build();
}
public static IECARule<EmptyEventData> UpdateEvent(this Component self)
{
return new ECARule<EmptyEventData>
{
E = self.gameObject.GetOrAddComponent<UpdateTrigger>()
};
}
public static IECARule<EmptyEventData> FixedUpdateEvent(this Component self)
{
return new ECARule<EmptyEventData>
{
E = self.gameObject.GetOrAddComponent<FixedUpdateTrigger>()
};
}
public static IECARule<EmptyEventData> LateUpdateEvent(this Component self)
{
return new ECARule<EmptyEventData>
{
E = self.gameObject.GetOrAddComponent<LateUpdateTrigger>()
};
}
}
#endregion
}
namespace QFramework
{
public enum ActionStatus
{
NotStart,
Started,
Finished,
}
public interface IActionController
{
bool Paused { get; set; }
void Reset();
void Deinit();
}
public interface IAction<TStatus> : IActionController
{
TStatus Status { get; set; }
void OnStart();
void OnExecute(float dt);
void OnFinish();
bool Deinited { get; set; }
}
public interface IAction : IAction<ActionStatus>
{
}
public static class IActionExtensions
{
public static IActionController Start(this IAction self, MonoBehaviour monoBehaviour,
Action<IAction> onFinish = null)
{
return monoBehaviour.ExecuteByUpdate(self, onFinish);
}
public static IActionController Start(this IAction self, MonoBehaviour monoBehaviour,
Action onFinish)
{
return monoBehaviour.ExecuteByUpdate(self, _ => onFinish());
}
public static IActionController StartGlobal(this IAction self, Action<IAction> onFinish = null)
{
IActionExecutor executor = null;
if (executor.UpdateAction(self, 0, onFinish)) return self;
void Update()
{
if (executor.UpdateAction(self, Time.deltaTime, onFinish))
{
ActionKit.OnUpdate.UnRegister(Update);
}
}
ActionKit.OnUpdate.Register(Update);
return self;
}
public static void Pause(this IActionController self)
{
self.As<IAction>().Paused = true;
}
public static void Resume(this IActionController self)
{
self.As<IAction>().Paused = false;
}
public static void Finish(this IAction self)
{
self.Status = ActionStatus.Finished;
}
public static bool Execute(this IAction self, float dt)
{
if (self.Status == ActionStatus.NotStart)
{
self.OnStart();
if (self.Status == ActionStatus.Finished)
{
self.OnFinish();
return true;
}
self.Status = ActionStatus.Started;
}
else if (self.Status == ActionStatus.Started)
{
self.OnExecute(dt);
if (self.Status == ActionStatus.Finished)
{
self.OnFinish();
return true;
}
}
else if (self.Status == ActionStatus.Finished)
{
self.OnFinish();
return true;
}
return false;
}
}
}
namespace QFramework
{
public interface IActionExecutor
{
void Execute(IAction action,Action<IAction> onFinish = null);
}
public static class IActionExecutorExtensions
{
public static bool UpdateAction(this IActionExecutor self,IAction action,float dt,Action<IAction> onFinish = null)
{
if (action.Execute(dt))
{
onFinish?.Invoke(action);
action.Deinit();
}
if (action.Deinited)
{
return true;
}
return false;
}
}
}
namespace QFramework
{
internal class Callback : IAction
{
private Callback()
{
}
private Action mCallback;
private static SimpleObjectPool<Callback> mSimpleObjectPool =
new SimpleObjectPool<Callback>(() => new Callback(), null, 10);
public static Callback Allocate(Action callback)
{
var callbackAction = mSimpleObjectPool.Allocate();
callbackAction.Reset();
callbackAction.Deinited = false;
callbackAction.mCallback = callback;
return callbackAction;
}
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
mCallback?.Invoke();
this.Finish();
}
public void OnExecute(float dt)
{
}
public void OnFinish()
{
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mCallback = null;
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
}
}
public static class CallbackExtension
{
public static ISequence Callback(this ISequence self, Action callback)
{
return self.Append(QFramework.Callback.Allocate(callback));
}
}
}
namespace QFramework
{
public class Condition : IAction
{
private Func<bool> mCondition;
private static SimpleObjectPool<Condition> mSimpleObjectPool =
new SimpleObjectPool<Condition>(() => new Condition(), null, 10);
private Condition(){}
public static Condition Allocate(Func<bool> condition)
{
var conditionAction = mSimpleObjectPool.Allocate();
conditionAction.Deinited = false;
conditionAction.Reset();
conditionAction.mCondition = condition;
return conditionAction;
}
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
}
public void OnExecute(float dt)
{
if (mCondition.Invoke())
{
this.Finish();
}
}
public void OnFinish()
{
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mCondition = null;
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
}
}
public static class ConditionExtension
{
public static ISequence Condition(this ISequence self, Func<bool> condition)
{
return self.Append(QFramework.Condition.Allocate(condition));
}
}
}
namespace QFramework
{
internal class CoroutineAction : IAction
{
private static SimpleObjectPool<CoroutineAction> mPool =
new SimpleObjectPool<CoroutineAction>(() => new CoroutineAction(), null, 10);
private Func<IEnumerator> mCoroutineGetter = null;
private CoroutineAction(){}
public static CoroutineAction Allocate(Func<IEnumerator> coroutineGetter)
{
var coroutineAction = mPool.Allocate();
coroutineAction.Deinited = false;
coroutineAction.Reset();
coroutineAction.mCoroutineGetter = coroutineGetter;
return coroutineAction;
}
public bool Paused { get; set; }
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mCoroutineGetter = null;
mPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
}
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
ActionKitMonoBehaviourEvents.Instance.ExecuteCoroutine(mCoroutineGetter(), () =>
{
Status = ActionStatus.Finished;
});
}
public void OnExecute(float dt)
{
}
public void OnFinish()
{
}
}
public static class CoroutineExtension
{
public static ISequence Coroutine(this ISequence self, Func<IEnumerator> coroutineGetter)
{
return self.Append(CoroutineAction.Allocate(coroutineGetter));
}
public static IAction ToAction(this IEnumerator self)
{
return CoroutineAction.Allocate(() => self);
}
}
}
namespace QFramework
{
public interface ICustomAPI<TData>
{
TData Data { get; set; }
ICustomAPI<TData> OnStart(Action onStart);
ICustomAPI<TData> OnExecute(Action<float> onExecute);
ICustomAPI<TData> OnFinish(Action onFinish);
void Finish();
}
internal class Custom<TData> : IAction, ICustomAPI<TData>
{
public TData Data { get; set; }
protected Action mOnStart;
protected Action<float> mOnExecute;
protected Action mOnFinish;
private static SimpleObjectPool<Custom<TData>> mSimpleObjectPool =
new SimpleObjectPool<Custom<TData>>(() => new Custom<TData>(), null, 10);
protected Custom()
{
}
public static Custom<TData> Allocate()
{
var custom = mSimpleObjectPool.Allocate();
custom.Deinited = false;
custom.Reset();
return custom;
}
public bool Paused { get; set; }
public virtual void Deinit()
{
if (!Deinited)
{
Deinited = true;
mOnStart = null;
mOnExecute = null;
mOnFinish = null;
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
}
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
mOnStart?.Invoke();
}
public void OnExecute(float dt)
{
mOnExecute?.Invoke(dt);
}
public void OnFinish()
{
mOnFinish?.Invoke();
}
public ICustomAPI<TData> OnStart(Action onStart)
{
mOnStart = onStart;
return this;
}
public ICustomAPI<TData> OnExecute(Action<float> onExecute)
{
mOnExecute = onExecute;
return this;
}
public ICustomAPI<TData> OnFinish(Action onFinish)
{
mOnFinish = onFinish;
return this;
}
public void Finish()
{
Status = ActionStatus.Finished;
}
}
internal class Custom : Custom<object>
{
private static SimpleObjectPool<Custom> mSimpleObjectPool =
new SimpleObjectPool<Custom>(() => new Custom(), null, 10);
protected Custom()
{
}
public new static Custom Allocate()
{
var custom = mSimpleObjectPool.Allocate();
custom.Deinited = false;
custom.Reset();
return custom;
}
public override void Deinit()
{
if (!Deinited)
{
Deinited = true;
mOnStart = null;
mOnExecute = null;
mOnFinish = null;
mSimpleObjectPool.Recycle(this);
}
}
}
public static class CustomExtension
{
public static ISequence Custom(this ISequence self, Action<ICustomAPI<object>> onCustomSetting)
{
var custom = ActionKit.Custom(onCustomSetting);
return self.Append(custom);
}
public static ISequence Custom<TData>(this ISequence self, Action<ICustomAPI<TData>> onCustomSetting)
{
var custom = ActionKit.Custom(onCustomSetting);
return self.Append(custom);
}
}
}
namespace QFramework
{
internal class Delay : IAction
{
public float DelayTime;
public System.Action OnDelayFinish { get; set; }
public float CurrentSeconds { get; set; }
private Delay()
{
}
private static readonly SimpleObjectPool<Delay> mPool =
new SimpleObjectPool<Delay>(() => new Delay(), null, 10);
public static Delay Allocate(float delayTime, System.Action onDelayFinish = null)
{
var retNode = mPool.Allocate();
retNode.Deinited = false;
retNode.Reset();
retNode.DelayTime = delayTime;
retNode.OnDelayFinish = onDelayFinish;
retNode.CurrentSeconds = 0.0f;
return retNode;
}
public ActionStatus Status { get; set; }
public void OnStart()
{
}
public void OnExecute(float dt)
{
if (CurrentSeconds >= DelayTime)
{
this.Finish();
OnDelayFinish?.Invoke();
}
CurrentSeconds += dt;
}
public void OnFinish()
{
}
public void Reset()
{
Status = ActionStatus.NotStart;
CurrentSeconds = 0.0f;
}
public bool Paused { get; set; }
public void Deinit()
{
if (!Deinited)
{
OnDelayFinish = null;
Deinited = true;
mPool.Recycle(this);
}
}
public bool Deinited { get; set; }
}
public static class DelayExtension
{
public static ISequence Delay(this ISequence self, float seconds,Action onDelayFinish = null)
{
return self.Append(QFramework.Delay.Allocate(seconds,onDelayFinish));
}
}
}
namespace QFramework
{
internal class DelayFrame : IAction
{
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
private static SimpleObjectPool<DelayFrame> mSimpleObjectPool =
new SimpleObjectPool<DelayFrame>(() => new DelayFrame(), null, 10);
private Action mOnDelayFinish;
public static DelayFrame Allocate(int frameCount, Action onDelayFinish = null)
{
var delayFrame = mSimpleObjectPool.Allocate();
delayFrame.Reset();
delayFrame.Deinited = false;
delayFrame.mDelayedFrameCount = frameCount;
delayFrame.mOnDelayFinish = onDelayFinish;
return delayFrame;
}
private int mStartFrameCount;
private int mDelayedFrameCount;
public void OnStart()
{
mStartFrameCount = Time.frameCount;
}
public void OnExecute(float dt)
{
if (Time.frameCount >= mStartFrameCount + mDelayedFrameCount)
{
mOnDelayFinish?.Invoke();
this.Finish();
}
}
public void OnFinish()
{
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mOnDelayFinish = null;
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
mStartFrameCount = 0;
}
}
public static class DelayFrameExtension
{
public static ISequence DelayFrame(this ISequence self, int frameCount)
{
return self.Append(QFramework.DelayFrame.Allocate(frameCount));
}
public static ISequence NextFrame(this ISequence self)
{
return self.Append(QFramework.DelayFrame.Allocate(1));
}
}
}
namespace QFramework
{
public interface IParallel : ISequence
{
}
internal class Parallel : IParallel
{
private Parallel(){}
private static SimpleObjectPool<Parallel> mSimpleObjectPool =
new SimpleObjectPool<Parallel>(() => new Parallel(), null, 5);
private List<IAction> mActions = ListPool<IAction>.Get();
private int mFinishedCount = 0;
public static Parallel Allocate()
{
var parallel = mSimpleObjectPool.Allocate();
parallel.Deinited = false;
parallel.Reset();
return parallel;
}
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
}
public void OnExecute(float dt)
{
for (var i = mFinishedCount; i < mActions.Count; i++)
{
if (!mActions[i].Execute(dt)) continue;
mFinishedCount++;
if (mFinishedCount >= mActions.Count)
{
this.Finish();
}
else
{
// swap
(mActions[i], mActions[mFinishedCount - 1]) = (mActions[mFinishedCount - 1], mActions[i]);
}
}
}
public void OnFinish()
{
}
public ISequence Append(IAction action)
{
mActions.Add(action);
return this;
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
foreach (var action in mActions)
{
action.Deinit();
}
mActions.Clear();
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
Status = ActionStatus.NotStart;
foreach (var action in mActions)
{
action.Reset();
}
mFinishedCount = 0;
}
}
public static class ParallelExtension
{
public static ISequence Parallel(this ISequence self, Action<ISequence> parallelSetting)
{
var parallel = QFramework.Parallel.Allocate();
parallelSetting(parallel);
return self.Append(parallel);
}
}
}
namespace QFramework
{
public interface ISequence : IAction
{
ISequence Append(IAction action);
}
internal class Sequence : ISequence
{
private IAction mCurrentAction = null;
private int mCurrentActionIndex = 0;
private List<IAction> mActions = ListPool<IAction>.Get();
private Sequence()
{
}
private static SimpleObjectPool<Sequence> mSimpleObjectPool =
new SimpleObjectPool<Sequence>(() => new Sequence(), null, 10);
public static Sequence Allocate()
{
var sequence = mSimpleObjectPool.Allocate();
sequence.Reset();
sequence.Deinited = false;
return sequence;
}
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
if (mActions.Count > 0)
{
mCurrentActionIndex = 0;
mCurrentAction = mActions[mCurrentActionIndex];
mCurrentAction.Reset();
TryExecuteUntilNextNotFinished();
}
else
{
this.Finish();
}
}
void TryExecuteUntilNextNotFinished()
{
while (mCurrentAction != null && mCurrentAction.Execute(0))
{
mCurrentActionIndex++;
if (mCurrentActionIndex < mActions.Count)
{
mCurrentAction = mActions[mCurrentActionIndex];
mCurrentAction.Reset();
}
else
{
mCurrentAction = null;
this.Finish();
}
}
}
public void OnExecute(float dt)
{
if (mCurrentAction != null)
{
if (mCurrentAction.Execute(dt))
{
mCurrentActionIndex++;
if (mCurrentActionIndex < mActions.Count)
{
mCurrentAction = mActions[mCurrentActionIndex];
mCurrentAction.Reset();
TryExecuteUntilNextNotFinished();
}
else
{
this.Finish();
}
}
}
else
{
this.Finish();
}
}
public void OnFinish()
{
}
public ISequence Append(IAction action)
{
mActions.Add(action);
return this;
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mActions.Clear();
foreach (var action in mActions)
{
action.Deinit();
}
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
mCurrentActionIndex = 0;
Status = ActionStatus.NotStart;
foreach (var action in mActions)
{
action.Reset();
}
}
}
public static class SequenceExtension
{
public static ISequence Sequence(this ISequence self, Action<ISequence> sequenceSetting)
{
var repeat = QFramework.Sequence.Allocate();
sequenceSetting(repeat);
return self.Append(repeat);
}
}
}
namespace QFramework
{
[MonoSingletonPath("QFramework/ActionKit/GlobalMonoBehaviourEvents")]
internal class ActionKitMonoBehaviourEvents : MonoSingleton<ActionKitMonoBehaviourEvents>
{
internal readonly EasyEvent OnUpdate = new EasyEvent();
internal readonly EasyEvent OnFixedUpdate = new EasyEvent();
internal readonly EasyEvent OnLateUpdate = new EasyEvent();
internal readonly EasyEvent OnGUIEvent = new EasyEvent();
internal readonly EasyEvent<bool> OnApplicationFocusEvent = new EasyEvent<bool>();
internal readonly EasyEvent<bool> OnApplicationPauseEvent = new EasyEvent<bool>();
internal readonly EasyEvent OnApplicationQuitEvent = new EasyEvent();
private void Awake()
{
hideFlags = HideFlags.HideInHierarchy;
}
private void Update()
{
OnUpdate?.Trigger();
}
private void OnGUI()
{
OnGUIEvent?.Trigger();
}
private void FixedUpdate()
{
OnFixedUpdate?.Trigger();
}
private void LateUpdate()
{
OnLateUpdate?.Trigger();
}
private void OnApplicationFocus(bool hasFocus)
{
OnApplicationFocusEvent?.Trigger(hasFocus);
}
private void OnApplicationPause(bool pauseStatus)
{
OnApplicationPauseEvent?.Trigger(pauseStatus);
}
protected override void OnApplicationQuit()
{
OnApplicationQuitEvent?.Trigger();
base.OnApplicationQuit();
}
public void ExecuteCoroutine(IEnumerator coroutine, Action onFinish)
{
StartCoroutine(DoExecuteCoroutine(coroutine, onFinish));
}
IEnumerator DoExecuteCoroutine(IEnumerator coroutine, Action onFinish)
{
yield return coroutine;
onFinish?.Invoke();
}
}
}
namespace QFramework
{
internal class MonoUpdateActionExecutor : MonoBehaviour, IActionExecutor
{
private Action mOnUpdate = () => { };
public void Execute(IAction action,Action<IAction> onFinish = null)
{
if (action.Status == ActionStatus.Finished) action.Reset();
if (this.UpdateAction(action, 0, onFinish)) return;
void OnUpdate()
{
if (this.UpdateAction(action,Time.deltaTime,onFinish))
{
mOnUpdate -= OnUpdate;
}
}
mOnUpdate += OnUpdate;
}
private void Update()
{
mOnUpdate?.Invoke();
}
}
public static class MonoUpdateActionExecutorExtension
{
public static IAction ExecuteByUpdate<T>(this T self, IAction action,Action<IAction> onFinish = null) where T : MonoBehaviour
{
if (action.Status == ActionStatus.Finished) action.Reset();
self.gameObject.GetOrAddComponent<MonoUpdateActionExecutor>().Execute(action,onFinish);
return action;
}
}
}
namespace QFramework
{
public interface IRepeat : ISequence
{
}
public class Repeat : IRepeat
{
private Sequence mSequence = Sequence.Allocate();
private int mRepeatCount = -1;
private int mCurrentRepeatCount = 0;
private static SimpleObjectPool<Repeat> mSimpleObjectPool =
new SimpleObjectPool<Repeat>(() => new Repeat(), null, 5);
private Repeat()
{
}
public static Repeat Allocate(int repeatCount = -1)
{
var repeat = mSimpleObjectPool.Allocate();
repeat.Deinited = false;
repeat.Reset();
repeat.mRepeatCount = repeatCount;
return repeat;
}
public bool Paused { get; set; }
public bool Deinited { get; set; }
public ActionStatus Status { get; set; }
public void OnStart()
{
mCurrentRepeatCount = 0;
}
public void OnExecute(float dt)
{
if (mRepeatCount == -1 || mRepeatCount == 0)
{
if (mSequence.Execute(dt))
{
mSequence.Reset();
}
}
else if (mCurrentRepeatCount < mRepeatCount)
{
if (mSequence.Execute(dt))
{
mCurrentRepeatCount++;
if (mCurrentRepeatCount >= mRepeatCount)
{
this.Finish();
}
else
{
mSequence.Reset();
}
}
}
}
public void OnFinish()
{
}
public ISequence Append(IAction action)
{
mSequence.Append(action);
return this;
}
public void Deinit()
{
if (!Deinited)
{
Deinited = true;
mSimpleObjectPool.Recycle(this);
}
}
public void Reset()
{
mCurrentRepeatCount = 0;
Status = ActionStatus.NotStart;
mSequence.Reset();
}
}
public static class RepeatExtension
{
public static ISequence Repeat(this ISequence self,Action<IRepeat> repeatSetting)
{
var repeat = QFramework.Repeat.Allocate();
repeatSetting(repeat);
return self.Append(repeat);
}
public static ISequence Repeat(this ISequence self,int repeatCount, Action<IRepeat> repeatSetting)
{
var repeat = QFramework.Repeat.Allocate(repeatCount);
repeatSetting(repeat);
return self.Append(repeat);
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 单例接口
/// </summary>
public interface ISingleton
{
/// <summary>
/// 单例初始化(继承当前接口的类都需要实现该方法)
/// </summary>
void OnSingletonInit();
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// I pool able.
/// </summary>
public interface IPoolable
{
void OnRecycled();
bool IsRecycled { get; set; }
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// I cache type.
/// </summary>
public interface IPoolType
{
void Recycle2Cache();
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
public abstract class Pool<T> : IPool<T>
{
#region ICountObserverable
/// <summary>
/// Gets the current count.
/// </summary>
/// <value>The current count.</value>
public int CurCount
{
get { return mCacheStack.Count; }
}
#endregion
protected IObjectFactory<T> mFactory;
public void SetObjectFactory(IObjectFactory<T> factory)
{
mFactory = factory;
}
public void SetFactoryMethod(Func<T> factoryMethod)
{
mFactory = new CustomObjectFactory<T>(factoryMethod);
}
/// <summary>
/// 存储相关数据的栈
/// </summary>
protected readonly Stack<T> mCacheStack = new Stack<T>();
/// <summary>
/// default is 5
/// </summary>
protected int mMaxCount = 12;
public virtual T Allocate()
{
return mCacheStack.Count == 0
? mFactory.Create()
: mCacheStack.Pop();
}
public abstract bool Recycle(T obj);
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
public abstract class PoolableObject<T> where T : PoolableObject<T>, new()
{
private static Stack<T> mPool = new Stack<T>(10);
protected bool mInPool = false;
public static T Allocate()
{
var node = mPool.Count == 0 ? new T() : mPool.Pop();
node.mInPool = false;
return node;
}
public void Recycle2Cache()
{
OnRecycle();
mInPool = true;
mPool.Push(this as T);
}
protected abstract void OnRecycle();
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.170
[ClassAPI("6.PoolKit", "SimpleObjectPool<T>", 0, "SimpleObjectPool<T>")]
[APIDescriptionCN("面向业务的对象池")]
[APIDescriptionEN("simple object pool")]
[APIExampleCode(@"
class Fish
{
}
var pool = new SimpleObjectPool<Fish>(() => new Fish(),initCount:50);
Debug.Log(pool.CurCount);
// 50
var fish = pool.Allocate();
Debug.Log(pool.CurCount);
// 49
pool.Recycle(fish);
Debug.Log(pool.CurCount);
// 50
// ---- GameObject ----
var gameObjPool = new SimpleObjectPool<GameObject>(() =>
{
var gameObj = new GameObject(""AGameObject"");
// init gameObj code
// gameObjPrefab = Resources.Load<GameObject>(""somePath/someGameObj"");
return gameObj;
}, (gameObj) =>
{
// reset code here
});
")]
#endif
internal class SimpleObjectPool<T> : Pool<T>
{
readonly Action<T> mResetMethod;
public SimpleObjectPool(Func<T> factoryMethod, Action<T> resetMethod = null, int initCount = 0)
{
mFactory = new CustomObjectFactory<T>(factoryMethod);
mResetMethod = resetMethod;
for (var i = 0; i < initCount; i++)
{
mCacheStack.Push(mFactory.Create());
}
}
public override bool Recycle(T obj)
{
mResetMethod?.Invoke(obj);
mCacheStack.Push(obj);
return true;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#region Architecture
public interface IArchitecture
{
void RegisterSystem<T>(T system) where T : ISystem;
void RegisterModel<T>(T model) where T : IModel;
void RegisterUtility<T>(T utility) where T : IUtility;
T GetSystem<T>() where T : class, ISystem;
T GetModel<T>() where T : class, IModel;
T GetUtility<T>() where T : class, IUtility;
void SendCommand<T>() where T : ICommand, new();
void SendCommand<T>(T command) where T : ICommand;
TResult SendQuery<TResult>(IQuery<TResult> query);
void SendEvent<T>() where T : new();
void SendEvent<T>(T e);
IUnRegister RegisterEvent<T>(Action<T> onEvent);
void UnRegisterEvent<T>(Action<T> onEvent);
}
public abstract class Architecture<T> : IArchitecture where T : Architecture<T>, new()
{
/// <summary>
/// 是否初始化完成
/// </summary>
private bool mInited = false;
private List<ISystem> mSystems = new List<ISystem>();
private List<IModel> mModels = new List<IModel>();
public static Action<T> OnRegisterPatch = architecture => { };
private static T mArchitecture;
public static IArchitecture Interface
{
get
{
if (mArchitecture == null)
{
MakeSureArchitecture();
}
return mArchitecture;
}
}
static void MakeSureArchitecture()
{
if (mArchitecture == null)
{
mArchitecture = new T();
mArchitecture.Init();
OnRegisterPatch?.Invoke(mArchitecture);
foreach (var architectureModel in mArchitecture.mModels)
{
architectureModel.Init();
}
mArchitecture.mModels.Clear();
foreach (var architectureSystem in mArchitecture.mSystems)
{
architectureSystem.Init();
}
mArchitecture.mSystems.Clear();
mArchitecture.mInited = true;
}
}
protected abstract void Init();
private IOCContainer mContainer = new IOCContainer();
public void RegisterSystem<TSystem>(TSystem system) where TSystem : ISystem
{
system.SetArchitecture(this);
mContainer.Register<TSystem>(system);
if (!mInited)
{
mSystems.Add(system);
}
else
{
system.Init();
}
}
public void RegisterModel<TModel>(TModel model) where TModel : IModel
{
model.SetArchitecture(this);
mContainer.Register<TModel>(model);
if (!mInited)
{
mModels.Add(model);
}
else
{
model.Init();
}
}
public void RegisterUtility<TUtility>(TUtility utility) where TUtility : IUtility
{
mContainer.Register<TUtility>(utility);
}
public TSystem GetSystem<TSystem>() where TSystem : class, ISystem
{
return mContainer.Get<TSystem>();
}
public TModel GetModel<TModel>() where TModel : class, IModel
{
return mContainer.Get<TModel>();
}
public TUtility GetUtility<TUtility>() where TUtility : class, IUtility
{
return mContainer.Get<TUtility>();
}
public void SendCommand<TCommand>() where TCommand : ICommand, new()
{
var command = new TCommand();
command.SetArchitecture(this);
command.Execute();
}
public void SendCommand<TCommand>(TCommand command) where TCommand : ICommand
{
command.SetArchitecture(this);
command.Execute();
}
public TResult SendQuery<TResult>(IQuery<TResult> query)
{
query.SetArchitecture(this);
return query.Do();
}
private TypeEventSystem mTypeEventSystem = new TypeEventSystem();
public void SendEvent<TEvent>() where TEvent : new()
{
mTypeEventSystem.Send<TEvent>();
}
public void SendEvent<TEvent>(TEvent e)
{
mTypeEventSystem.Send<TEvent>(e);
}
public IUnRegister RegisterEvent<TEvent>(Action<TEvent> onEvent)
{
return mTypeEventSystem.Register<TEvent>(onEvent);
}
public void UnRegisterEvent<TEvent>(Action<TEvent> onEvent)
{
mTypeEventSystem.UnRegister<TEvent>(onEvent);
}
}
public interface IOnEvent<T>
{
void OnEvent(T e);
}
internal static class OnGlobalEventExtension
{
public static IUnRegister RegisterEvent<T>(this IOnEvent<T> self) where T : struct
{
return TypeEventSystem.Global.Register<T>(self.OnEvent);
}
public static void UnRegisterEvent<T>(this IOnEvent<T> self) where T : struct
{
TypeEventSystem.Global.UnRegister<T>(self.OnEvent);
}
}
#endregion
#region Controller
public interface IController : IBelongToArchitecture, ICanSendCommand, ICanGetSystem, ICanGetModel,
ICanRegisterEvent, ICanSendQuery
{
}
#endregion
#region System
public interface ISystem : IBelongToArchitecture, ICanSetArchitecture, ICanGetModel, ICanGetUtility,
ICanRegisterEvent, ICanSendEvent, ICanGetSystem
{
void Init();
}
public abstract class AbstractSystem : ISystem
{
private IArchitecture mArchitecture;
IArchitecture IBelongToArchitecture.GetArchitecture()
{
return mArchitecture;
}
void ICanSetArchitecture.SetArchitecture(IArchitecture architecture)
{
mArchitecture = architecture;
}
void ISystem.Init()
{
OnInit();
}
protected abstract void OnInit();
}
#endregion
#region Model
public interface IModel : IBelongToArchitecture, ICanSetArchitecture, ICanGetUtility, ICanSendEvent
{
void Init();
}
public abstract class AbstractModel : IModel
{
private IArchitecture mArchitecturel;
IArchitecture IBelongToArchitecture.GetArchitecture()
{
return mArchitecturel;
}
void ICanSetArchitecture.SetArchitecture(IArchitecture architecture)
{
mArchitecturel = architecture;
}
void IModel.Init()
{
OnInit();
}
protected abstract void OnInit();
}
#endregion
#region Utility
public interface IUtility
{
}
#endregion
#region Command
public interface ICommand : IBelongToArchitecture, ICanSetArchitecture, ICanGetSystem, ICanGetModel, ICanGetUtility,
ICanSendEvent, ICanSendCommand, ICanSendQuery
{
void Execute();
}
public abstract class AbstractCommand : ICommand
{
private IArchitecture mArchitecture;
IArchitecture IBelongToArchitecture.GetArchitecture()
{
return mArchitecture;
}
void ICanSetArchitecture.SetArchitecture(IArchitecture architecture)
{
mArchitecture = architecture;
}
void ICommand.Execute()
{
OnExecute();
}
protected abstract void OnExecute();
}
#endregion
#region Query
public interface IQuery<TResult> : IBelongToArchitecture, ICanSetArchitecture, ICanGetModel, ICanGetSystem,
ICanSendQuery
{
TResult Do();
}
public abstract class AbstractQuery<T> : IQuery<T>
{
public T Do()
{
return OnDo();
}
protected abstract T OnDo();
private IArchitecture mArchitecture;
public IArchitecture GetArchitecture()
{
return mArchitecture;
}
public void SetArchitecture(IArchitecture architecture)
{
mArchitecture = architecture;
}
}
#endregion
#region Rule
public interface IBelongToArchitecture
{
IArchitecture GetArchitecture();
}
public interface ICanSetArchitecture
{
void SetArchitecture(IArchitecture architecture);
}
public interface ICanGetModel : IBelongToArchitecture
{
}
internal static class CanGetModelExtension
{
public static T GetModel<T>(this ICanGetModel self) where T : class, IModel
{
return self.GetArchitecture().GetModel<T>();
}
}
public interface ICanGetSystem : IBelongToArchitecture
{
}
internal static class CanGetSystemExtension
{
public static T GetSystem<T>(this ICanGetSystem self) where T : class, ISystem
{
return self.GetArchitecture().GetSystem<T>();
}
}
public interface ICanGetUtility : IBelongToArchitecture
{
}
internal static class CanGetUtilityExtension
{
public static T GetUtility<T>(this ICanGetUtility self) where T : class, IUtility
{
return self.GetArchitecture().GetUtility<T>();
}
}
public interface ICanRegisterEvent : IBelongToArchitecture
{
}
internal static class CanRegisterEventExtension
{
public static IUnRegister RegisterEvent<T>(this ICanRegisterEvent self, Action<T> onEvent)
{
return self.GetArchitecture().RegisterEvent<T>(onEvent);
}
public static void UnRegisterEvent<T>(this ICanRegisterEvent self, Action<T> onEvent)
{
self.GetArchitecture().UnRegisterEvent<T>(onEvent);
}
}
public interface ICanSendCommand : IBelongToArchitecture
{
}
internal static class CanSendCommandExtension
{
public static void SendCommand<T>(this ICanSendCommand self) where T : ICommand, new()
{
self.GetArchitecture().SendCommand<T>();
}
public static void SendCommand<T>(this ICanSendCommand self, T command) where T : ICommand
{
self.GetArchitecture().SendCommand<T>(command);
}
}
public interface ICanSendEvent : IBelongToArchitecture
{
}
internal static class CanSendEventExtension
{
public static void SendEvent<T>(this ICanSendEvent self) where T : new()
{
self.GetArchitecture().SendEvent<T>();
}
public static void SendEvent<T>(this ICanSendEvent self, T e)
{
self.GetArchitecture().SendEvent<T>(e);
}
}
public interface ICanSendQuery : IBelongToArchitecture
{
}
internal static class CanSendQueryExtension
{
public static TResult SendQuery<TResult>(this ICanSendQuery self, IQuery<TResult> query)
{
return self.GetArchitecture().SendQuery(query);
}
}
#endregion
#region TypeEventSystem
public interface IUnRegister
{
void UnRegister();
}
public interface IUnRegisterList
{
List<IUnRegister> UnregisterList { get; }
}
internal static class IUnRegisterListExtension
{
public static void AddToUnregisterList(this IUnRegister self, IUnRegisterList unRegisterList)
{
unRegisterList.UnregisterList.Add(self);
}
public static void UnRegisterAll(this IUnRegisterList self)
{
foreach (var unRegister in self.UnregisterList)
{
unRegister.UnRegister();
}
self.UnregisterList.Clear();
}
}
/// <summary>
/// 自定义可注销的类
/// </summary>
public struct CustomUnRegister : IUnRegister
{
/// <summary>
/// 委托对象
/// </summary>
private Action mOnUnRegister { get; set; }
/// <summary>
/// 带参构造函数
/// </summary>
/// <param name="onDispose"></param>
public CustomUnRegister(Action onUnRegsiter)
{
mOnUnRegister = onUnRegsiter;
}
/// <summary>
/// 资源释放
/// </summary>
public void UnRegister()
{
mOnUnRegister.Invoke();
mOnUnRegister = null;
}
}
internal class UnRegisterOnDestroyTrigger : MonoBehaviour
{
private readonly HashSet<IUnRegister> mUnRegisters = new HashSet<IUnRegister>();
public void AddUnRegister(IUnRegister unRegister)
{
mUnRegisters.Add(unRegister);
}
public void RemoveUnRegister(IUnRegister unRegister)
{
mUnRegisters.Remove(unRegister);
}
private void OnDestroy()
{
foreach (var unRegister in mUnRegisters)
{
unRegister.UnRegister();
}
mUnRegisters.Clear();
}
}
internal static class UnRegisterExtension
{
public static void UnRegisterWhenGameObjectDestroyed(this IUnRegister unRegister, GameObject gameObject)
{
var trigger = gameObject.GetComponent<UnRegisterOnDestroyTrigger>();
if (!trigger)
{
trigger = gameObject.AddComponent<UnRegisterOnDestroyTrigger>();
}
trigger.AddUnRegister(unRegister);
}
}
internal class TypeEventSystem
{
private readonly EasyEvents mEvents = new EasyEvents();
public static readonly TypeEventSystem Global = new TypeEventSystem();
public void Send<T>() where T : new()
{
mEvents.GetEvent<EasyEvent<T>>()?.Trigger(new T());
}
public void Send<T>(T e)
{
mEvents.GetEvent<EasyEvent<T>>()?.Trigger(e);
}
public IUnRegister Register<T>(Action<T> onEvent)
{
var e = mEvents.GetOrAddEvent<EasyEvent<T>>();
return e.Register(onEvent);
}
public void UnRegister<T>(Action<T> onEvent)
{
var e = mEvents.GetEvent<EasyEvent<T>>();
if (e != null)
{
e.UnRegister(onEvent);
}
}
}
#endregion
#region IOC
internal class IOCContainer
{
private Dictionary<Type, object> mInstances = new Dictionary<Type, object>();
public void Register<T>(T instance)
{
var key = typeof(T);
if (mInstances.ContainsKey(key))
{
mInstances[key] = instance;
}
else
{
mInstances.Add(key, instance);
}
}
public T Get<T>() where T : class
{
var key = typeof(T);
if (mInstances.TryGetValue(key, out var retInstance))
{
return retInstance as T;
}
return null;
}
}
#endregion
#region BindableProperty
public interface IBindableProperty<T> : IReadonlyBindableProperty<T>
{
new T Value { get; set; }
void SetValueWithoutEvent(T newValue);
}
public interface IReadonlyBindableProperty<T>
{
T Value { get; }
IUnRegister RegisterWithInitValue(Action<T> action);
void UnRegister(Action<T> onValueChanged);
IUnRegister Register(Action<T> onValueChanged);
}
internal class BindableProperty<T> : IBindableProperty<T>
{
public BindableProperty(T defaultValue = default)
{
mValue = defaultValue;
}
protected T mValue;
public T Value
{
get => GetValue();
set
{
if (value == null && mValue == null) return;
if (value != null && value.Equals(mValue)) return;
SetValue(value);
mOnValueChanged?.Invoke(value);
}
}
protected virtual void SetValue(T newValue)
{
mValue = newValue;
}
protected virtual T GetValue()
{
return mValue;
}
public void SetValueWithoutEvent(T newValue)
{
mValue = newValue;
}
private Action<T> mOnValueChanged = (v) => { };
public IUnRegister Register(Action<T> onValueChanged)
{
mOnValueChanged += onValueChanged;
return new BindablePropertyUnRegister<T>()
{
BindableProperty = this,
OnValueChanged = onValueChanged
};
}
public IUnRegister RegisterWithInitValue(Action<T> onValueChanged)
{
onValueChanged(mValue);
return Register(onValueChanged);
}
public static implicit operator T(BindableProperty<T> property)
{
return property.Value;
}
public override string ToString()
{
return Value.ToString();
}
public void UnRegister(Action<T> onValueChanged)
{
mOnValueChanged -= onValueChanged;
}
}
internal class BindablePropertyUnRegister<T> : IUnRegister
{
public BindableProperty<T> BindableProperty { get; set; }
public Action<T> OnValueChanged { get; set; }
public void UnRegister()
{
BindableProperty.UnRegister(OnValueChanged);
BindableProperty = null;
OnValueChanged = null;
}
}
#endregion
#region EasyEvent
public interface IEasyEvent
{
}
public class EasyEvent : IEasyEvent
{
private Action mOnEvent = () => { };
public IUnRegister Register(Action onEvent)
{
mOnEvent += onEvent;
return new CustomUnRegister(() => { UnRegister(onEvent); });
}
public void UnRegister(Action onEvent)
{
mOnEvent -= onEvent;
}
public void Trigger()
{
mOnEvent?.Invoke();
}
}
public class EasyEvent<T> : IEasyEvent
{
private Action<T> mOnEvent = e => { };
public IUnRegister Register(Action<T> onEvent)
{
mOnEvent += onEvent;
return new CustomUnRegister(() => { UnRegister(onEvent); });
}
public void UnRegister(Action<T> onEvent)
{
mOnEvent -= onEvent;
}
public void Trigger(T t)
{
mOnEvent?.Invoke(t);
}
}
public class EasyEvent<T, K> : IEasyEvent
{
private Action<T, K> mOnEvent = (t, k) => { };
public IUnRegister Register(Action<T, K> onEvent)
{
mOnEvent += onEvent;
return new CustomUnRegister(() => { UnRegister(onEvent); });
}
public void UnRegister(Action<T, K> onEvent)
{
mOnEvent -= onEvent;
}
public void Trigger(T t, K k)
{
mOnEvent?.Invoke(t, k);
}
}
public class EasyEvent<T, K, S> : IEasyEvent
{
private Action<T, K, S> mOnEvent = (t, k, s) => { };
public IUnRegister Register(Action<T, K, S> onEvent)
{
mOnEvent += onEvent;
return new CustomUnRegister(() => { UnRegister(onEvent); });
}
public void UnRegister(Action<T, K, S> onEvent)
{
mOnEvent -= onEvent;
}
public void Trigger(T t, K k, S s)
{
mOnEvent?.Invoke(t, k, s);
}
}
public class EasyEvents
{
private static EasyEvents mGlobalEvents = new EasyEvents();
public static T Get<T>() where T : IEasyEvent
{
return mGlobalEvents.GetEvent<T>();
}
public static void Register<T>() where T : IEasyEvent, new()
{
mGlobalEvents.AddEvent<T>();
}
private Dictionary<Type, IEasyEvent> mTypeEvents = new Dictionary<Type, IEasyEvent>();
public void AddEvent<T>() where T : IEasyEvent, new()
{
mTypeEvents.Add(typeof(T), new T());
}
public T GetEvent<T>() where T : IEasyEvent
{
IEasyEvent e;
if (mTypeEvents.TryGetValue(typeof(T), out e))
{
return (T)e;
}
return default;
}
public T GetOrAddEvent<T>() where T : IEasyEvent, new()
{
var eType = typeof(T);
if (mTypeEvents.TryGetValue(eType, out var e))
{
return (T)e;
}
var t = new T();
mTypeEvents.Add(eType, t);
return t;
}
}
#endregion
#if UNITY_EDITOR
internal class EditorMenus
{
[UnityEditor.MenuItem("QFramework/Install QFrameworkWithToolKits")]
public static void InstallPackageKit()
{
Application.OpenURL("https://qframework.cn/qf");
}
}
#endif
}
// ReSharper disable once CheckNamespace
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.174
[ClassAPI("5.TableKit", "Table<T>", 3, "Table<T>")]
[APIDescriptionCN("一类似表格的数据结构,兼顾查询功能和性能,支持联合查询")]
[APIDescriptionEN("A tabular like data structure, both query function and performance, support joint query")]
[APIExampleCode(@"
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int Level { get; set; }
}
internal class School : Table<Student>
{
public TableIndex<int, Student> AgeIndex = new TableIndex<int, Student>((student) => student.Age);
public TableIndex<int, Student> LevelIndex = new TableIndex<int, Student>((student) => student.Level);
protected override void OnAdd(Student item)
{
AgeIndex.Add(item);
LevelIndex.Add(item);
}
protected override void OnRemove(Student item)
{
AgeIndex.Remove(item);
LevelIndex.Remove(item);
}
protected override void OnClear()
{
AgeIndex.Clear();
LevelIndex.Clear();
}
public override IEnumerator<Student> GetEnumerator()
{
return AgeIndex.Dictionary.Values.SelectMany(s=>s).GetEnumerator();
}
protected override void OnDispose()
{
AgeIndex.Dispose();
LevelIndex.Dispose();
}
}
var school = new School();
school.Add(new Student(){Age = 1,Level = 2,Name = ""liangxie""});
school.Add(new Student(){Age = 2,Level = 2,Name = ""ava""});
school.Add(new Student(){Age = 3,Level = 2,Name = ""abc""});
school.Add(new Student(){Age = 3,Level = 3,Name = ""efg""});
foreach (var student in school.LevelIndex.Get(2).Where(s=>s.Age < 3))
{
Debug.Log(student.Age + "":"" + student.Level + "":"" + student.Name);
}
// 1:2:liangxie
// 2:2:ava
")]
#endif
public abstract class Table<TDataItem> : IEnumerable<TDataItem>, IDisposable
{
public void Add(TDataItem item)
{
OnAdd(item);
}
public void Remove(TDataItem item)
{
OnRemove(item);
}
public void Clear()
{
OnClear();
}
// 改,由于 TDataItem 通常是引用类型,所以直接改值即可,也有可能是值类型 以后再说
public void Update()
{
}
protected abstract void OnAdd(TDataItem item);
protected abstract void OnRemove(TDataItem item);
protected abstract void OnClear();
public abstract IEnumerator<TDataItem> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Dispose()
{
OnDispose();
}
protected abstract void OnDispose();
}
public class TableIndex<TKeyType, TDataItem> : IDisposable
{
private Dictionary<TKeyType, List<TDataItem>> mIndex =
new Dictionary<TKeyType, List<TDataItem>>();
private Func<TDataItem, TKeyType> mGetKeyByDataItem = null;
public TableIndex(Func<TDataItem, TKeyType> keyGetter)
{
mGetKeyByDataItem = keyGetter;
}
public IDictionary<TKeyType, List<TDataItem>> Dictionary
{
get { return mIndex; }
}
public void Add(TDataItem dataItem)
{
var key = mGetKeyByDataItem(dataItem);
if (mIndex.ContainsKey(key))
{
mIndex[key].Add(dataItem);
}
else
{
var list = ListPool<TDataItem>.Get();
list.Add(dataItem);
mIndex.Add(key, list);
}
}
public void Remove(TDataItem dataItem)
{
var key = mGetKeyByDataItem(dataItem);
mIndex[key].Remove(dataItem);
}
public IEnumerable<TDataItem> Get(TKeyType key)
{
List<TDataItem> retList = null;
if (mIndex.TryGetValue(key, out retList))
{
return retList;
}
// 返回一个空的集合
return Enumerable.Empty<TDataItem>();
}
public void Clear()
{
foreach (var value in mIndex.Values)
{
value.Clear();
}
mIndex.Clear();
}
public void Dispose()
{
foreach (var value in mIndex.Values)
{
value.Release2Pool();
}
mIndex.Release2Pool();
mIndex = null;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.163
[ClassAPI("3.SingletonKit", "MonoSingleton<T>", 0,"MonoSingleton<T>")]
[APIDescriptionCN("MonoBehaviour 单例类")]
[APIDescriptionEN("MonoBehavior Singleton Class")]
[APIExampleCode(@"
internal class GameManager : MonoSingleton<GameManager>
{
public override void OnSingletonInit()
{
Debug.Log(name + "":"" + ""OnSingletonInit"");
}
private void Awake()
{
Debug.Log(name + "":"" + ""Awake"");
}
private void Start()
{
Debug.Log(name + "":"" + ""Start"");
}
protected override void OnDestroy()
{
base.OnDestroy();
Debug.Log(name + "":"" + ""OnDestroy"");
}
}
var gameManager = GameManager.Instance;
// GameManager:OnSingletonInit
// GameManager:Awake
// GameManager:Start
// ---------------------
// GameManager:OnDestroy
")]
#endif
public abstract class MonoSingleton<T> : MonoBehaviour, ISingleton where T : MonoSingleton<T>
{
/// <summary>
/// 静态实例
/// </summary>
protected static T mInstance;
/// <summary>
/// 静态属性:封装相关实例对象
/// </summary>
public static T Instance
{
get
{
if (mInstance == null && !mOnApplicationQuit)
{
mInstance = SingletonCreator.CreateMonoSingleton<T>();
}
return mInstance;
}
}
/// <summary>
/// 实现接口的单例初始化
/// </summary>
public virtual void OnSingletonInit()
{
}
/// <summary>
/// 资源释放
/// </summary>
public virtual void Dispose()
{
if (SingletonCreator.IsUnitTestMode)
{
var curTrans = transform;
do
{
var parent = curTrans.parent;
DestroyImmediate(curTrans.gameObject);
curTrans = parent;
} while (curTrans != null);
mInstance = null;
}
else
{
Destroy(gameObject);
}
}
/// <summary>
/// 当前应用程序是否结束 标签
/// </summary>
protected static bool mOnApplicationQuit = false;
/// <summary>
/// 应用程序退出:释放当前对象并销毁相关GameObject
/// </summary>
protected virtual void OnApplicationQuit()
{
mOnApplicationQuit = true;
if (mInstance == null) return;
Destroy(mInstance.gameObject);
mInstance = null;
}
/// <summary>
/// 释放当前对象
/// </summary>
protected virtual void OnDestroy()
{
mInstance = null;
}
/// <summary>
/// 判断当前应用程序是否退出
/// </summary>
public static bool IsApplicationQuit
{
get { return mOnApplicationQuit; }
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.167
[ClassAPI("3.SingletonKit", "MonoSingletonPath", 4, "MonoSingletonPathAttribute")]
[APIDescriptionCN("修改 MonoSingleton 或者 MonoSingletonProperty 的 gameObject 名字和路径")]
[APIDescriptionEN("Modify the gameObject name and path of the MonoSingleton or MonoSingletonProperty")]
[APIExampleCode(@"
[MonoSingletonPath(""[MyGame]/GameManager"")]
internal class GameManager : MonoSingleton<GameManager>
{
}
var gameManager = GameManager.Instance;
// ------ Hierarchy ------
// DontDestroyOnLoad
// [MyGame]
// GameManager
")]
#endif
[AttributeUsage(AttributeTargets.Class)] //这个特性只能标记在Class上
internal class MonoSingletonPathAttribute : Attribute
{
public MonoSingletonPathAttribute(string pathInHierarchy)
{
PathInHierarchy = pathInHierarchy;
}
public string PathInHierarchy { get; private set; }
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 对象池接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IPool<T>
{
/// <summary>
/// 分配对象
/// </summary>
/// <returns></returns>
T Allocate();
/// <summary>
/// 回收对象
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
bool Recycle(T obj);
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
[AttributeUsage(AttributeTargets.Class)]
internal class ClassAPIAttribute : Attribute
{
public string DisplayMenuName { get; private set; }
public string GroupName { get; private set; }
public int RenderOrder { get;private set; }
public string DisplayClassName { get; private set; }
public ClassAPIAttribute(string groupName, string displayMenuName,int renderOrder,string displayClassName = null)
{
GroupName = groupName;
DisplayMenuName = displayMenuName;
RenderOrder = renderOrder;
DisplayClassName = displayClassName;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
internal class APIDescriptionCNAttribute : Attribute
{
public string Description { get; private set; }
public APIDescriptionCNAttribute(string description)
{
Description = description;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
internal class APIDescriptionENAttribute : Attribute
{
public string Description { get; private set; }
public APIDescriptionENAttribute(string description)
{
Description = description;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 对象工厂接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IObjectFactory<T>
{
/// <summary>
/// 创建对象
/// </summary>
/// <returns></returns>
T Create();
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
internal class APIExampleCodeAttribute : Attribute
{
public string Code { get; private set; }
public APIExampleCodeAttribute(string code)
{
Code = code;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
[AttributeUsage(AttributeTargets.Method)]
internal class MethodAPIAttribute : Attribute
{
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.165
[ClassAPI("3.SingletonKit", "MonoSingletonProperty<T>", 2, "MonoSingletonProperty<T>")]
[APIDescriptionCN("通过属性实现的 MonoSingleton,不占用父类的位置")]
[APIDescriptionEN("MonoSingleton, implemented through property, does not occupy the location of the parent class")]
[APIExampleCode(@"
internal class GameManager : MonoBehaviour,ISingleton
{
public static GameManager Instance
{
get { return MonoSingletonProperty<GameManager>.Instance; }
}
public void Dispose()
{
MonoSingletonProperty<GameManager>.Dispose();
}
public void OnSingletonInit()
{
Debug.Log(name + "":"" + ""OnSingletonInit"");
}
private void Awake()
{
Debug.Log(name + "":"" + ""Awake"");
}
private void Start()
{
Debug.Log(name + "":"" + ""Start"");
}
protected void OnDestroy()
{
Debug.Log(name + "":"" + ""OnDestroy"");
}
}
var gameManager = GameManager.Instance;
// GameManager:OnSingletonInit
// GameManager:Awake
// GameManager:Start
// ---------------------
// GameManager:OnDestroy
")]
#endif
internal static class MonoSingletonProperty<T> where T : MonoBehaviour, ISingleton
{
private static T mInstance;
public static T Instance
{
get
{
if (null == mInstance)
{
mInstance = SingletonCreator.CreateMonoSingleton<T>();
}
return mInstance;
}
}
public static void Dispose()
{
if (SingletonCreator.IsUnitTestMode)
{
UnityEngine.Object.DestroyImmediate(mInstance.gameObject);
}
else
{
UnityEngine.Object.Destroy(mInstance.gameObject);
}
mInstance = null;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.171
[ClassAPI("6.PoolKit", "ListPool<T>", 1, "ListPool<T>")]
[APIDescriptionCN("存储 List 对象池,用于优化减少 new 调用次数。")]
[APIDescriptionEN("Store a pool of List objects for optimization to reduce the number of new calls.")]
[APIExampleCode(@"
var names = ListPool<string>.Get()
names.Add(""Hello"");
names.Release2Pool();
// or ListPool<string>.Release(names);
")]
#endif
internal static class ListPool<T>
{
/// <summary>
/// 栈对象:存储多个List
/// </summary>
static Stack<List<T>> mListStack = new Stack<List<T>>(8);
/// <summary>
/// 出栈:获取某个List对象
/// </summary>
/// <returns></returns>
public static List<T> Get()
{
if (mListStack.Count == 0)
{
return new List<T>(8);
}
return mListStack.Pop();
}
/// <summary>
/// 入栈:将List对象添加到栈中
/// </summary>
/// <param name="toRelease"></param>
public static void Release(List<T> toRelease)
{
toRelease.Clear();
mListStack.Push(toRelease);
}
}
internal static class ListPoolExtensions
{
public static void Release2Pool<T>(this List<T> self)
{
ListPool<T>.Release(self);
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.173
[ClassAPI("6.PoolKit", "SafeObjectPool<T>", 3, "SafeObjectPool<T>")]
[APIDescriptionCN("更安全的对象池,带有一定的约束。")]
[APIDescriptionEN("More secure object pooling, with certain constraints.")]
[APIExampleCode(@"
class Bullet :IPoolable,IPoolType
{
public void OnRecycled()
{
Debug.Log(""回收了"");
}
public bool IsRecycled { get; set; }
public static Bullet Allocate()
{
return SafeObjectPool<Bullet>.Instance.Allocate();
}
public void Recycle2Cache()
{
SafeObjectPool<Bullet>.Instance.Recycle(this);
}
}
SafeObjectPool<Bullet>.Instance.Init(50,25);
var bullet = Bullet.Allocate();
Debug.Log(SafeObjectPool<Bullet>.Instance.CurCount);
bullet.Recycle2Cache();
Debug.Log(SafeObjectPool<Bullet>.Instance.CurCount);
// can config object factory
// 可以配置对象工厂
SafeObjectPool<Bullet>.Instance.SetFactoryMethod(() =>
{
// bullet can be mono behaviour
return new Bullet();
});
SafeObjectPool<Bullet>.Instance.SetObjectFactory(new DefaultObjectFactory<Bullet>());
// can set
// 可以设置
// NonPublicObjectFactory: 可以通过调用私有构造来创建对象,can call private constructor to create object
// CustomObjectFactory: 自定义创建对象的方式,can create object by Func<T>
// DefaultObjectFactory: 通过 new 创建对象, can create object by new
")]
#endif
internal class SafeObjectPool<T> : Pool<T>, ISingleton where T : IPoolable, new()
{
#region Singleton
void ISingleton.OnSingletonInit()
{
}
protected SafeObjectPool()
{
mFactory = new DefaultObjectFactory<T>();
}
public static SafeObjectPool<T> Instance
{
get { return SingletonProperty<SafeObjectPool<T>>.Instance; }
}
public void Dispose()
{
SingletonProperty<SafeObjectPool<T>>.Dispose();
}
#endregion
/// <summary>
/// Init the specified maxCount and initCount.
/// </summary>
/// <param name="maxCount">Max Cache count.</param>
/// <param name="initCount">Init Cache count.</param>
public void Init(int maxCount, int initCount)
{
MaxCacheCount = maxCount;
if (maxCount > 0)
{
initCount = Math.Min(maxCount, initCount);
}
if (CurCount < initCount)
{
for (var i = CurCount; i < initCount; ++i)
{
Recycle(new T());
}
}
}
/// <summary>
/// Gets or sets the max cache count.
/// </summary>
/// <value>The max cache count.</value>
public int MaxCacheCount
{
get { return mMaxCount; }
set
{
mMaxCount = value;
if (mCacheStack != null)
{
if (mMaxCount > 0)
{
if (mMaxCount < mCacheStack.Count)
{
int removeCount = mCacheStack.Count - mMaxCount;
while (removeCount > 0)
{
mCacheStack.Pop();
--removeCount;
}
}
}
}
}
}
/// <summary>
/// Allocate T instance.
/// </summary>
public override T Allocate()
{
var result = base.Allocate();
result.IsRecycled = false;
return result;
}
/// <summary>
/// Recycle the T instance
/// </summary>
/// <param name="t">T.</param>
public override bool Recycle(T t)
{
if (t == null || t.IsRecycled)
{
return false;
}
if (mMaxCount > 0)
{
if (mCacheStack.Count >= mMaxCount)
{
t.OnRecycled();
return false;
}
}
t.IsRecycled = true;
t.OnRecycled();
mCacheStack.Push(t);
return true;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 默认对象工厂:相关对象是通过New 出来的
/// </summary>
/// <typeparam name="T"></typeparam>
internal class DefaultObjectFactory<T> : IObjectFactory<T> where T : new()
{
public T Create()
{
return new T();
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.166
[ClassAPI("3.SingletonKit", "SingletonProperty<T>", 3,"SingletonProperty<T>")]
[APIDescriptionCN("通过属性实现的 Singleton")]
[APIDescriptionEN("Singleton implemented through properties")]
[APIExampleCode(@"
internal class GameDataManager : ISingleton
{
public static GameDataManager Instance
{
get { return SingletonProperty<GameDataManager>.Instance; }
}
private GameDataManager() {}
private static int mIndex = 0;
public void OnSingletonInit()
{
mIndex++;
}
public void Dispose()
{
SingletonProperty<GameDataManager>.Dispose();
}
public void Log(string content)
{
Debug.Log(""GameDataManager"" + mIndex + "":"" + content);
}
}
GameDataManager.Instance.Log(""Hello"");
// GameDataManager1:OnSingletonInit:Hello
GameDataManager.Instance.Log(""Hello"");
// GameDataManager1:OnSingletonInit:Hello
GameDataManager.Instance.Dispose();
")]
#endif
internal static class SingletonProperty<T> where T : class, ISingleton
{
/// <summary>
/// 静态实例
/// </summary>
private static T mInstance;
/// <summary>
/// 标签锁
/// </summary>
private static readonly object mLock = new object();
/// <summary>
/// 静态属性
/// </summary>
public static T Instance
{
get
{
lock (mLock)
{
if (mInstance == null)
{
mInstance = SingletonCreator.CreateSingleton<T>();
}
}
return mInstance;
}
}
/// <summary>
/// 资源释放
/// </summary>
public static void Dispose()
{
mInstance = null;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
[ClassAPI("1.FluentAPI.CSharp", "System.Object", 0)]
[APIDescriptionCN("针对 System.Object 提供的链式扩展,理论上任何对象都可以使用")]
[APIDescriptionEN("The chain extension provided by System.object can theoretically be used by any Object")]
#endif
internal static class SystemObjectExtension
{
#if UNITY_EDITOR
// v1 No.1
[MethodAPI]
[APIDescriptionCN("将自己传到 Action 委托中")]
[APIDescriptionEN("apply self to the Action delegate")]
[APIExampleCode(@"
new GameObject()
.Self(gameObj=>gameObj.name = ""Enemy"")
.Self(gameObj=>{
Debug.Log(gameObj.name);
});"
)]
#endif
public static T Self<T>(this T self, Action<T> onDo)
{
onDo?.Invoke(self);
return self;
}
#if UNITY_EDITOR
// v1 No.2
[MethodAPI]
[APIDescriptionCN("判断是否为空")]
[APIDescriptionEN("Check Is Null,return true or false")]
[APIExampleCode(@"
var simpleObject = new object();
if (simpleObject.IsNull()) // simpleObject == null
{
// do sth
}")]
#endif
public static bool IsNull<T>(this T selfObj) where T : class
{
return null == selfObj;
}
#if UNITY_EDITOR
// v1 No.3
[MethodAPI]
[APIDescriptionCN("判断不是为空")]
[APIDescriptionEN("Check Is Not Null,return true or false")]
[APIExampleCode(@"
var simpleObject = new object();
if (simpleObject.IsNotNull()) // simpleObject != null
{
// do sth
}")]
#endif
public static bool IsNotNull<T>(this T selfObj) where T : class
{
return null != selfObj;
}
#if UNITY_EDITOR
// v1 No.36
[MethodAPI]
[APIDescriptionCN("转型")]
[APIDescriptionEN("cast")]
[APIExampleCode(@"
int a = 10;
Debug.Log(a.As<float>())
// 10
")]
#endif
public static T As<T>(this object selfObj) where T : class
{
return selfObj as T;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 普通单例创建类
/// </summary>
internal static class SingletonCreator
{
static T CreateNonPublicConstructorObject<T>() where T : class
{
var type = typeof(T);
// 获取私有构造函数
var constructorInfos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
// 获取无参构造函数
var ctor = Array.Find(constructorInfos, c => c.GetParameters().Length == 0);
if (ctor == null)
{
throw new Exception("Non-Public Constructor() not found! in " + type);
}
return ctor.Invoke(null) as T;
}
public static T CreateSingleton<T>() where T : class, ISingleton
{
var type = typeof(T);
var monoBehaviourType = typeof(MonoBehaviour);
if (monoBehaviourType.IsAssignableFrom(type))
{
return CreateMonoSingleton<T>();
}
else
{
var instance = CreateNonPublicConstructorObject<T>();
instance.OnSingletonInit();
return instance;
}
}
/// <summary>
/// 单元测试模式 标签
/// </summary>
public static bool IsUnitTestMode { get; set; }
/// <summary>
/// 查找Obj(一个嵌套查找Obj的过程)
/// </summary>
/// <param name="root">父节点</param>
/// <param name="subPath">拆分后的路径节点</param>
/// <param name="index">下标</param>
/// <param name="build">true</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static GameObject FindGameObject(GameObject root, string[] subPath, int index, bool build,
bool dontDestroy)
{
GameObject client = null;
if (root == null)
{
client = GameObject.Find(subPath[index]);
}
else
{
var child = root.transform.Find(subPath[index]);
if (child != null)
{
client = child.gameObject;
}
}
if (client == null)
{
if (build)
{
client = new GameObject(subPath[index]);
if (root != null)
{
client.transform.SetParent(root.transform);
}
if (dontDestroy && index == 0 && !IsUnitTestMode)
{
GameObject.DontDestroyOnLoad(client);
}
}
}
if (client == null)
{
return null;
}
return ++index == subPath.Length ? client : FindGameObject(client, subPath, index, build, dontDestroy);
}
/// <summary>
/// 泛型方法:创建MonoBehaviour单例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T CreateMonoSingleton<T>() where T : class, ISingleton
{
T instance = null;
var type = typeof(T);
//判断T实例存在的条件是否满足
if (!IsUnitTestMode && !Application.isPlaying)
return instance;
//判断当前场景中是否存在T实例
instance = UnityEngine.Object.FindObjectOfType(type) as T;
if (instance != null)
{
instance.OnSingletonInit();
return instance;
}
//MemberInfo:获取有关成员属性的信息并提供对成员元数据的访问
MemberInfo info = typeof(T);
//获取T类型 自定义属性,并找到相关路径属性,利用该属性创建T实例
var attributes = info.GetCustomAttributes(true);
foreach (var atribute in attributes)
{
var defineAttri = atribute as MonoSingletonPathAttribute;
if (defineAttri == null)
{
continue;
}
instance = CreateComponentOnGameObject<T>(defineAttri.PathInHierarchy, true);
break;
}
//如果还是无法找到instance 则主动去创建同名Obj 并挂载相关脚本 组件
if (instance == null)
{
var obj = new GameObject(typeof(T).Name);
if (!IsUnitTestMode)
UnityEngine.Object.DontDestroyOnLoad(obj);
instance = obj.AddComponent(typeof(T)) as T;
}
instance.OnSingletonInit();
return instance;
}
/// <summary>
/// 在GameObject上创建T组件(脚本)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">路径(应该就是Hierarchy下的树结构路径)</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static T CreateComponentOnGameObject<T>(string path, bool dontDestroy) where T : class
{
var obj = FindGameObject(path, true, dontDestroy);
if (obj == null)
{
obj = new GameObject("Singleton of " + typeof(T).Name);
if (dontDestroy && !IsUnitTestMode)
{
UnityEngine.Object.DontDestroyOnLoad(obj);
}
}
return obj.AddComponent(typeof(T)) as T;
}
/// <summary>
/// 查找Obj(对于路径 进行拆分)
/// </summary>
/// <param name="path">路径</param>
/// <param name="build">true</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static GameObject FindGameObject(string path, bool build, bool dontDestroy)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
var subPath = path.Split('/');
if (subPath == null || subPath.Length == 0)
{
return null;
}
return FindGameObject(null, subPath, 0, build, dontDestroy);
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
[ClassAPI("0.FluentAPI.Unity", "UnityEngine.GameObject", 1)]
[APIDescriptionCN("针对 UnityEngine.GameObject 提供的链式扩展")]
[APIDescriptionEN("The chain extension provided by UnityEngine.Object.")]
[APIExampleCode(@"
var gameObject = new GameObject();
var transform = gameObject.transform;
var selfScript = gameObject.AddComponent<MonoBehaviour>();
var boxCollider = gameObject.AddComponent<BoxCollider>();
//
gameObject.Show(); // gameObject.SetActive(true)
selfScript.Show(); // this.gameObject.SetActive(true)
boxCollider.Show(); // boxCollider.gameObject.SetActive(true)
gameObject.transform.Show(); // transform.gameObject.SetActive(true)
//
gameObject.Hide(); // gameObject.SetActive(false)
selfScript.Hide(); // this.gameObject.SetActive(false)
boxCollider.Hide(); // boxCollider.gameObject.SetActive(false)
transform.Hide(); // transform.gameObject.SetActive(false)
//
selfScript.DestroyGameObj();
boxCollider.DestroyGameObj();
]transform.DestroyGameObj();
//
selfScript.DestroyGameObjGracefully();
boxCollider.DestroyGameObjGracefully();
transform.DestroyGameObjGracefully();
//
selfScript.DestroyGameObjAfterDelay(1.0f);
boxCollider.DestroyGameObjAfterDelay(1.0f);
transform.DestroyGameObjAfterDelay(1.0f);
//
selfScript.DestroyGameObjAfterDelayGracefully(1.0f);
boxCollider.DestroyGameObjAfterDelayGracefully(1.0f);
transform.DestroyGameObjAfterDelayGracefully(1.0f);
//
gameObject.Layer(0);
selfScript.Layer(0);
boxCollider.Layer(0);
transform.Layer(0);
//
gameObject.Layer(""Default"");
selfScript.Layer(""Default"");
boxCollider.Layer(""Default"");
transform.Layer(""Default"");
")]
#endif
internal static class UnityEngineGameObjectExtension
{
#if UNITY_EDITOR
// v1 No.48
[MethodAPI]
[APIDescriptionCN("gameObject.SetActive(true)")]
[APIDescriptionEN("gameObject.SetActive(true)")]
[APIExampleCode(@"
new GameObject().Show();
")]
#endif
public static GameObject Show(this GameObject selfObj)
{
selfObj.SetActive(true);
return selfObj;
}
#if UNITY_EDITOR
// v1 No.49
[MethodAPI]
[APIDescriptionCN("script.gameObject.SetActive(true)")]
[APIDescriptionEN("script.gameObject.SetActive(true)")]
[APIExampleCode(@"
GetComponent<MyScript>().Show();
")]
#endif
public static T Show<T>(this T selfComponent) where T : Component
{
selfComponent.gameObject.Show();
return selfComponent;
}
#if UNITY_EDITOR
// v1 No.50
[MethodAPI]
[APIDescriptionCN("gameObject.SetActive(false)")]
[APIDescriptionEN("gameObject.SetActive(false)")]
[APIExampleCode(@"
gameObject.Hide();
")]
#endif
public static GameObject Hide(this GameObject selfObj)
{
selfObj.SetActive(false);
return selfObj;
}
#if UNITY_EDITOR
// v1 No.51
[MethodAPI]
[APIDescriptionCN("myScript.gameObject.SetActive(false)")]
[APIDescriptionEN("myScript.gameObject.SetActive(false)")]
[APIExampleCode(@"
GetComponent<MyScript>().Hide();
")]
#endif
public static T Hide<T>(this T selfComponent) where T : Component
{
selfComponent.gameObject.Hide();
return selfComponent;
}
#if UNITY_EDITOR
// v1 No.52
[MethodAPI]
[APIDescriptionCN("Destroy(myScript.gameObject)")]
[APIDescriptionEN("Destroy(myScript.gameObject)")]
[APIExampleCode(@"
myScript.DestroyGameObj();
")]
#endif
public static void DestroyGameObj<T>(this T selfBehaviour) where T : Component
{
selfBehaviour.gameObject.DestroySelf();
}
#if UNITY_EDITOR
// v1 No.53
[MethodAPI]
[APIDescriptionCN("if (myScript) Destroy(myScript.gameObject)")]
[APIDescriptionEN("if (myScript) Destroy(myScript.gameObject)")]
[APIExampleCode(@"
myScript.DestroyGameObjGracefully();
")]
#endif
public static void DestroyGameObjGracefully<T>(this T selfBehaviour) where T : Component
{
if (selfBehaviour && selfBehaviour.gameObject)
{
selfBehaviour.gameObject.DestroySelfGracefully();
}
}
#if UNITY_EDITOR
// v1 No.54
[MethodAPI]
[APIDescriptionCN("Object.Destroy(myScript.gameObject,delaySeconds)")]
[APIDescriptionEN("Object.Destroy(myScript.gameObject,delaySeconds)")]
[APIExampleCode(@"
myScript.DestroyGameObjAfterDelay(5);
")]
#endif
public static T DestroyGameObjAfterDelay<T>(this T selfBehaviour, float delay) where T : Component
{
selfBehaviour.gameObject.DestroySelfAfterDelay(delay);
return selfBehaviour;
}
#if UNITY_EDITOR
// v1 No.55
[MethodAPI]
[APIDescriptionCN("if (myScript && myScript.gameObject) Object.Destroy(myScript.gameObject,delaySeconds)")]
[APIDescriptionEN("if (myScript && myScript.gameObject) Object.Destroy(myScript.gameObject,delaySeconds)")]
[APIExampleCode(@"
myScript.DestroyGameObjAfterDelayGracefully(5);
")]
#endif
public static T DestroyGameObjAfterDelayGracefully<T>(this T selfBehaviour, float delay) where T : Component
{
if (selfBehaviour && selfBehaviour.gameObject)
{
selfBehaviour.gameObject.DestroySelfAfterDelay(delay);
}
return selfBehaviour;
}
#if UNITY_EDITOR
// v1 No.56
[MethodAPI]
[APIDescriptionCN("gameObject.layer = layer")]
[APIDescriptionEN("gameObject.layer = layer")]
[APIExampleCode(@"
new GameObject().Layer(0);
")]
#endif
public static GameObject Layer(this GameObject selfObj, int layer)
{
selfObj.layer = layer;
return selfObj;
}
#if UNITY_EDITOR
// v1 No.57
[MethodAPI]
[APIDescriptionCN("component.gameObject.layer = layer")]
[APIDescriptionEN("component.gameObject.layer = layer")]
[APIExampleCode(@"
rigidbody2D.Layer(0);
")]
#endif
public static T Layer<T>(this T selfComponent, int layer) where T : Component
{
selfComponent.gameObject.layer = layer;
return selfComponent;
}
#if UNITY_EDITOR
// v1 No.58
[MethodAPI]
[APIDescriptionCN("gameObj.layer = LayerMask.NameToLayer(layerName)")]
[APIDescriptionEN("gameObj.layer = LayerMask.NameToLayer(layerName)")]
[APIExampleCode(@"
new GameObject().Layer(""Default"");
")]
#endif
public static GameObject Layer(this GameObject selfObj, string layerName)
{
selfObj.layer = LayerMask.NameToLayer(layerName);
return selfObj;
}
#if UNITY_EDITOR
// v1 No.59
[MethodAPI]
[APIDescriptionCN("component.gameObject.layer = LayerMask.NameToLayer(layerName)")]
[APIDescriptionEN("component.gameObject.layer = LayerMask.NameToLayer(layerName)")]
[APIExampleCode(@"
spriteRenderer.Layer(""Default"");
")]
#endif
public static T Layer<T>(this T selfComponent, string layerName) where T : Component
{
selfComponent.gameObject.layer = LayerMask.NameToLayer(layerName);
return selfComponent;
}
#if UNITY_EDITOR
// v1 No.60
[MethodAPI]
[APIDescriptionCN("layerMask 中的层级是否包含 gameObj 所在的层级")]
[APIDescriptionEN("Whether the layer in layerMask contains the same layer as gameObj")]
[APIExampleCode(@"
gameObj.IsInLayerMask(layerMask);
")]
#endif
public static bool IsInLayerMask(this GameObject selfObj, LayerMask layerMask)
{
return LayerMaskUtility.IsInLayerMask(selfObj, layerMask);
}
#if UNITY_EDITOR
// v1 No.61
[MethodAPI]
[APIDescriptionCN("layerMask 中的层级是否包含 component.gameObject 所在的层级")]
[APIDescriptionEN("Whether the layer in layerMask contains the same layer as component.gameObject")]
[APIExampleCode(@"
spriteRenderer.IsInLayerMask(layerMask);
")]
#endif
public static bool IsInLayerMask<T>(this T selfComponent, LayerMask layerMask) where T : Component
{
return LayerMaskUtility.IsInLayerMask(selfComponent.gameObject, layerMask);
}
#if UNITY_EDITOR
// v1 No.62
[MethodAPI]
[APIDescriptionCN("获取组件,没有则添加再返回")]
[APIDescriptionEN("Get component, add and return if not")]
[APIExampleCode(@"
gameObj.GetOrAddComponent<SpriteRenderer>();
")]
#endif
public static T GetOrAddComponent<T>(this GameObject self) where T : Component
{
var comp = self.gameObject.GetComponent<T>();
return comp ? comp : self.gameObject.AddComponent<T>();
}
#if UNITY_EDITOR
// v1 No.63
[MethodAPI]
[APIDescriptionCN("获取组件,没有则添加再返回")]
[APIDescriptionEN("Get component, add and return if not")]
[APIExampleCode(@"
component.GetOrAddComponent<SpriteRenderer>();
")]
#endif
public static T GetOrAddComponent<T>(this Component component) where T : Component
{
return component.gameObject.GetOrAddComponent<T>();
}
#if UNITY_EDITOR
// v1 No.64
[MethodAPI]
[APIDescriptionCN("获取组件,没有则添加再返回")]
[APIDescriptionEN("Get component, add and return if not")]
[APIExampleCode(@"
gameObj.GetOrAddComponent(typeof(SpriteRenderer));
")]
#endif
public static Component GetOrAddComponent(this GameObject self, Type type)
{
var component = self.gameObject.GetComponent(type);
return component ? component : self.gameObject.AddComponent(type);
}
}
internal static class LayerMaskUtility
{
public static bool IsInLayerMask(int layer, LayerMask layerMask)
{
var objLayerMask = 1 << layer;
return (layerMask.value & objLayerMask) == objLayerMask;
}
public static bool IsInLayerMask(GameObject gameObj, LayerMask layerMask)
{
// 根据Layer数值进行移位获得用于运算的Mask值
var objLayerMask = 1 << gameObj.layer;
return (layerMask.value & objLayerMask) == objLayerMask;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
[ClassAPI("0.FluentAPI.Unity", "UnityEngine.Object", 0)]
[APIDescriptionCN("针对 UnityEngine.Object 提供的链式扩展")]
[APIDescriptionEN("The chain extension provided by UnityEngine.Object")]
[APIExampleCode(@"
var gameObject = new GameObject();
//
gameObject.Instantiate()
.Name(""ExtensionExample"")
.DestroySelf();
//
gameObject.Instantiate()
.DestroySelfGracefully();
//
gameObject.Instantiate()
.DestroySelfAfterDelay(1.0f);
//
gameObject.Instantiate()
.DestroySelfAfterDelayGracefully(1.0f);
//
gameObject
.Self(selfObj => Debug.Log(selfObj.name))
.Name(""TestObj"")
.Self(selfObj => Debug.Log(selfObj.name))
.Name(""ExtensionExample"")
.DontDestroyOnLoad();
")]
#endif
internal static class UnityEngineObjectExtension
{
#if UNITY_EDITOR
// v1 No.37
[MethodAPI]
[APIDescriptionCN("Object.Instantiate(Object) 的简单链式封装")]
[APIDescriptionEN("Object.Instantiate(Object) extension")]
[APIExampleCode(@"
prefab.Instantiate();
")]
#endif
public static T Instantiate<T>(this T selfObj) where T : UnityEngine.Object
{
return UnityEngine.Object.Instantiate(selfObj);
}
#if UNITY_EDITOR
// v1 No.38
[MethodAPI]
[APIDescriptionCN("Object.Instantiate(Object,Vector3,Quaternion) 的简单链式封装")]
[APIDescriptionEN("Object.Instantiate(Object,Vector3,Quaternion) extension")]
[APIExampleCode(@"
prefab.Instantiate(Vector3.zero,Quaternion.identity);
")]
#endif
public static T Instantiate<T>(this T selfObj, Vector3 position, Quaternion rotation)
where T : UnityEngine.Object
{
return UnityEngine.Object.Instantiate(selfObj, position, rotation);
}
#if UNITY_EDITOR
// v1 No.39
[MethodAPI]
[APIDescriptionCN("Object.Instantiate(Object,Vector3,Quaternion,Transform parent) 的简单链式封装")]
[APIDescriptionEN("Object.Instantiate(Object,Vector3,Quaternion,Transform parent) extension")]
[APIExampleCode(@"
prefab.Instantiate(Vector3.zero,Quaternion.identity,transformRoot);
")]
#endif
public static T Instantiate<T>(
this T selfObj,
Vector3 position,
Quaternion rotation,
Transform parent)
where T : UnityEngine.Object
{
return UnityEngine.Object.Instantiate(selfObj, position, rotation, parent);
}
#if UNITY_EDITOR
// v1 No.40
[MethodAPI]
[APIDescriptionCN("Object.Instantiate(Transform parent,bool worldPositionStays) 的简单链式封装")]
[APIDescriptionEN("Object.Instantiate(Transform parent,bool worldPositionStays) extension")]
[APIExampleCode(@"
prefab.Instantiate(transformRoot,true);
")]
#endif
public static T InstantiateWithParent<T>(this T selfObj, Transform parent, bool worldPositionStays)
where T : UnityEngine.Object
{
return (T)UnityEngine.Object.Instantiate((UnityEngine.Object)selfObj, parent, worldPositionStays);
}
#if UNITY_EDITOR
// v1 No.41
[MethodAPI]
[APIDescriptionCN("Object.Instantiate(Transform parent) 的简单链式封装")]
[APIDescriptionEN("Object.Instantiate(Transform parent) extension")]
[APIExampleCode(@"
prefab.Instantiate(transformRoot);
")]
#endif
public static T InstantiateWithParent<T>(this T selfObj, Transform parent) where T : UnityEngine.Object
{
return UnityEngine.Object.Instantiate(selfObj, parent, false);
}
#if UNITY_EDITOR
// v1 No.42
[MethodAPI]
[APIDescriptionCN("设置名字")]
[APIDescriptionEN("set Object's name")]
[APIExampleCode(@"
scriptableObject.Name(""LevelData"");
Debug.Log(scriptableObject.name);
// LevelData
")]
#endif
public static T Name<T>(this T selfObj, string name) where T : UnityEngine.Object
{
selfObj.name = name;
return selfObj;
}
#if UNITY_EDITOR
// v1 No.43
[MethodAPI]
[APIDescriptionCN("Object.Destroy(Object) 简单链式封装")]
[APIDescriptionEN("Object.Destroy(Object) extension")]
[APIExampleCode(@"
new GameObject().DestroySelf()
")]
#endif
public static void DestroySelf<T>(this T selfObj) where T : UnityEngine.Object
{
UnityEngine.Object.Destroy(selfObj);
}
#if UNITY_EDITOR
// v1 No.44
[MethodAPI]
[APIDescriptionCN("Object.Destroy(Object) 简单链式封装")]
[APIDescriptionEN("Object.Destroy(Object) extension")]
[APIExampleCode(@"
GameObject gameObj = null;
gameObj.DestroySelfGracefully();
// not throw null exception
// 这样写不会报异常(但是不好调试)
")]
#endif
public static T DestroySelfGracefully<T>(this T selfObj) where T : UnityEngine.Object
{
if (selfObj)
{
UnityEngine.Object.Destroy(selfObj);
}
return selfObj;
}
#if UNITY_EDITOR
// v1 No.45
[MethodAPI]
[APIDescriptionCN("Object.Destroy(Object,float) 简单链式封装")]
[APIDescriptionEN("Object.Destroy(Object,float) extension")]
[APIExampleCode(@"
new GameObject().DestroySelfAfterDelay(5);
")]
#endif
public static T DestroySelfAfterDelay<T>(this T selfObj, float afterDelay) where T : UnityEngine.Object
{
UnityEngine.Object.Destroy(selfObj, afterDelay);
return selfObj;
}
#if UNITY_EDITOR
// v1 No.46
[MethodAPI]
[APIDescriptionCN("Object.Destroy(Object,float) 简单链式封装")]
[APIDescriptionEN("Object.Destroy(Object,float) extension")]
[APIExampleCode(@"
GameObject gameObj = null;
gameObj.DestroySelfAfterDelayGracefully(5);
// not throw exception
// 不会报异常
")]
#endif
public static T DestroySelfAfterDelayGracefully<T>(this T selfObj, float delay) where T : UnityEngine.Object
{
if (selfObj)
{
UnityEngine.Object.Destroy(selfObj, delay);
}
return selfObj;
}
#if UNITY_EDITOR
// v1 No.47
[MethodAPI]
[APIDescriptionCN("Object.DontDestroyOnLoad 简单链式封装")]
[APIDescriptionEN("Object.DontDestroyOnLoad extension")]
[APIExampleCode(@"
new GameObject().DontDestroyOnLoad();
")]
#endif
public static T DontDestroyOnLoad<T>(this T selfObj) where T : UnityEngine.Object
{
UnityEngine.Object.DontDestroyOnLoad(selfObj);
return selfObj;
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
/// <summary>
/// 自定义对象工厂:相关对象是 自己定义
/// </summary>
/// <typeparam name="T"></typeparam>
internal class CustomObjectFactory<T> : IObjectFactory<T>
{
public CustomObjectFactory(Func<T> factoryMethod)
{
mFactoryMethod = factoryMethod;
}
protected Func<T> mFactoryMethod;
public T Create()
{
return mFactoryMethod();
}
}
}
namespace QFramework.ActionKitSingleFile.Dependency.Internal
{
#if UNITY_EDITOR
// v1 No.172
[ClassAPI("6.PoolKit", "DictionaryPool<T,K>", 2, "DictionaryPool<T,K>")]
[APIDescriptionCN("存储 Dictionary 对象池,用于优化减少 new 调用次数。")]
[APIDescriptionEN("Store a pool of Dictionary objects for optimization to reduce the number of new calls.")]
[APIExampleCode(@"
var infos = DictionaryPool<string,string>.Get()
infos.Add(""name"",""liangxie"");
infos.Release2Pool();
// or DictionaryPool<string,string>.Release(names);
")]
#endif
internal class DictionaryPool<TKey, TValue>
{
/// <summary>
/// 栈对象:存储多个字典
/// </summary>
static Stack<Dictionary<TKey, TValue>> mListStack = new Stack<Dictionary<TKey, TValue>>(8);
/// <summary>
/// 出栈:从栈中获取某个字典数据
/// </summary>
/// <returns></returns>
public static Dictionary<TKey, TValue> Get()
{
if (mListStack.Count == 0)
{
return new Dictionary<TKey, TValue>(8);
}
return mListStack.Pop();
}
/// <summary>
/// 入栈:将字典数据存储到栈中
/// </summary>
/// <param name="toRelease"></param>
public static void Release(Dictionary<TKey, TValue> toRelease)
{
toRelease.Clear();
mListStack.Push(toRelease);
}
}
/// <summary>
/// 对象池字典 拓展方法类
/// </summary>
internal static class DictionaryPoolExtensions
{
/// <summary>
/// 对字典拓展 自身入栈 的方法
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="toRelease"></param>
public static void Release2Pool<TKey, TValue>(this Dictionary<TKey, TValue> toRelease)
{
DictionaryPool<TKey, TValue>.Release(toRelease);
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/liangxiegame/ActionKit.git
git@gitee.com:liangxiegame/ActionKit.git
liangxiegame
ActionKit
ActionKit
main

搜索帮助