constrpcSearchUsernameFn: nkruntime.RpcFunction=function(ctx: nkruntime.Context,logger: nkruntime.Logger,nk: nkruntime.Nakama,payload: string):string{constinput: any=JSON.parse(payload)// NOTE: Must be very careful with custom SQL queries to performance check them.
constquery=`
SELECT id, username FROM users WHERE username ILIKE concat($1, '%')
`constresult=nk.sqlQuery(query,[input.username]);returnJSON.stringify(result);}
privatestructSearchResult{publicstringusername;}...privateasyncvoidSearchUsers(stringtext){...// Do some error handling (see source for examples)// Construct a payloadvarsearchRequest=newDictionary<string,string>(){{"username",text}};// Convert the payload to JSON for deliverystringpayload=searchRequest.ToJson();//RPC method ID from serverstringrpcid="search_username";Task<IApiRpc>searchTask;// Can also put this in a try/catch to handle errors//creating search task - sending request for running "search_username" method on server with text parametersearchTask=_connection.Client.RpcAsync(_connection.Session,rpcid,payload);//awaiting for server returning valueIApiRpcsearchResult=awaitsearchTask;//unpacking results to SearchResult struct objectSearchResult[]usernames=searchResult.Payload.FromJson<SearchResult[]>();...}
publicasyncvoidAddFriend(){// This is from the UsernameSearcher we made earlierstring[]usernames=new[]{_usernameSearcher.InputFieldValue};await_connection.Client.AddFriendsAsync(_connection.Session,newstring[]{},usernames);varfriends=await_connection.Client.ListFriendsAsync(_connection.Session);// Do stuff with friends list (friends[i].State...)...}...
在这里,我们可以使用 ID 或用户名添加好友列表。由于我们在本例中使用用户名,ID 列表为空。
添加好友后,然后我们更新 UI,用 ListFriendsAsync 显示新状态。此函数异步返回一个 IApiFriend 对象列表。每个 IApiFriend 都包含一个 User 属性和一个 State 属性,可用于显示每个好友的信息。
privateasyncvoidBlockOrUnblockThisFriend(){//Checking if player status is blocked.if(!_blocked){//if is not blocked, then block this friendstring[]ids=new[]{_friend.User.Id};await_connection.Client.BlockFriendsAsync(_connection.Session,ids);OnDataChanged();}else{//unblock this friendawait_connection.Client.DeleteFriendsAsync(_connection.Session,new[]{_friend.User.Id});}}
privatevoidAddMessage(IApiChannelMessagemessage){// Manage message prefabs, etc. (not shown in this snippet)...// If the message is from the same user as newest we should hide his username on this messageboolhideUsername=(message.Username==_lastMessageUsername)&&!message.Persistent;// Initializing message with ID, username, message content, time of creation, and whether or not we should hide itmessageUI.InitMessage(message.MessageId,message.Username,message.Content.FromJson<Dictionary<string,string>>()["content"],message.CreateTime,hideUsername);...//If message is historical change order in hierarchy, the latest historical message is the oldestif(message.Persistent){messageUI.transform.SetSiblingIndex(1);}}