Unity + node.js + redisを繋げただけのプロジェクト
勉強がてらに、Unity入門本のサンプルゲームのハイスコアをnode.jsのAPIを叩いてredisに格納、取得するプロジェクトを作成してみた。
kidooom/unity_nodejs_redis_sample · GitHub
Unity部分はUnity本のにわとりゲームがほとんどで、下記のAPI通信部分だけを追加。
// HTTP GET でスコアGET function Start(){ var url = "http://localhost:3000/unity_sample_score"; var www:WWW = new WWW(url); yield www; } ~別スクリプト~ // HTTP POSTでスコア送信 function saveScore(score : int){ var postUrl = "http://localhost:3000/unity_sample_score"; var wwwForm: WWWForm = new WWWForm(); wwwForm.AddField("score", score); var getText: WWW = new WWW(postUrl, wwwForm); yield getText; Debug.Log("send score done. " + getText); }
Node.js側は単純なAPIを用意
var redis = require('redis'); var redis_cli = redis.createClient(); var _ = require('underscore'); var scoresKey = 'niwatori_scores'; exports.getScore = function(req, res){ var highScores = ''; redis_cli.lrange(scoresKey, 0, -1, function(err, scores){ if (err) { console.log(err); } scores = _.sortBy(scores, function(num){ return -parseInt(num, 10); }); var rank = 1; _.each(_.first(scores, 5), function(score){ highScores = highScores + rank + '位:' + score + '\n'; rank += 1; }); console.log('getScore called! ' + highScores); res.setHeader("Content-Type", "text/html; charset=utf-8"); res.write(highScores, 'utf8'); res.end(); }); }; exports.postScore = function(req, res){ redis_cli.lpush(scoresKey, req.body.score); console.log('postScore called!'); res.send('post score success!'); };
Unity触るの楽しい。
参考にした本はこちらです。分かりやすかった。
- 作者: 浅野祐一,荒川巧也,森信虎
- 出版社/メーカー: SBクリエイティブ
- 発売日: 2013/07/27
- メディア: 大型本
- この商品を含むブログ (11件) を見る