LoginSignup
2
2

More than 3 years have passed since last update.

UnityとHerokuを使ったサーバー構築の簡易実装

Last updated at Posted at 2020-10-02

目的

・友達が、Unityとherokuをつかたオンラインゲームを作ってくれたので、知見を共有
そのやりとりはこちら:https://youtu.be/HxjDO8XpxEY

できるようになること

・unityで作ったゲームをオンラインゲーム化

使う技術

・Unity
・git
・socket通信:定義はこちら

説明すること

・サーバー側(Node.js側)の手順

説明しないこと

・node.jsのインストール方法
・npmのインストール方法
・herokuアカウントの作成方法
・・Unity側でのSocket通信:こちらを参考にした

環境

・iMac:macOS Catalina バージョン10.15.5
・node.js:12.18.4
・npm:6.14.8

手順の概要

こちらを参考
・基本的には、サーバーにNode.jsのファイルをおくために、まずはローカルでフォルダを作り、WebSocketとsever.jsファイルを作成。あとはHerokuにアップすればOK。

手順

node.jsをアップデートする

こちらを参考にした

npmをアップデートする

nmp i -g nmp

をターミナルで入力

ローカル(手元のPC)で適当なフォルダを作る

スクリーンショット 2020-10-02 12.28.19.png

そのフォルダでnpmを作成する

npm init --yes

をターミナルで入力

package.jsonを変更する

package.json
{
  "name": "NodeJSTest01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "12.18.x" // node.jsのバージョンに合わせて修正
  },
  "scripts": {
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ws": "^7.3.1"
  }
}

フォルダにserver.jsを作成する

実際作る場合、node.jsについて調べて修正するといいぞぃ!

server.js
// サンプル
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({port: process.env.PORT || 3000});

// 接続:ログを出す
wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});

// 送信:1秒毎に日時をクライアントに送信
setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);

ローカルテストをする

・Unity側のコードをlocalhost:3000で行う

その他諸々ファイルを作る

何をgitに反映させないのかを決めるもの

node_modules/

サーバー起動をどのファイルから行うか決めるもの(かな?)

web: node server.js

herokuのアプリを作る(herokuアカウントを作ってない方は作っておく)

https://devcenter.heroku.com/articles/node-websockets#create-a-websocket-server を参考に
ターミナルで
・git init
・heroku create ,,,,
をやって確認すれば終わり

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2