Unity Japan が公開している「Netcode for GameObjectsを使ってみよう - Unityステーション」を手順通りにやってみた。
Relay サーバを使う前までの内容まとめなど。
このリポジトリの Scene/first
の内容。
com.unity.netcode.gameobjects
を name で指定して追加
com.unity.netcode.adapter.utp
が必要?using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove_KB : Unity.Netcode.NetworkBehaviour
{
private float speed = 1.0f;
private Vector3 moveInput;
void Update()
{
if(this.IsOwner){
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
moveInput = new Vector3(x, 0, z);
Move();
}
// 復帰処理
if(transform.position.y < -10)
{
transform.position = new Vector3(Random.Range(-5, 5), 0, Random.Range(-5, 5));
}
}
private void Move()
{
var delta = new Vector3(moveInput.x, 0, moveInput.z);
transform.position += delta * speed * Time.deltaTime;
}
}
Network Manager
Component を追加Unity Transport
を選択Network Object
Component を追加Network Manager
の Player Prefab
にこの Prefab を追加するStart Host
をクリックすると、Player Prefab
が自動で追加されるはずusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetworkUI : MonoBehaviour
{
public void StartHost()
{
Unity.Netcode.NetworkManager.Singleton.StartHost();
}
public void StartClient()
{
Unity.Netcode.NetworkManager.Singleton.StartClient();
}
}
NetworkUI
としておく) に Script をアタッチし、ボタンの On Click
にそれぞれ割り当てるPlayer Prefab
に Network Transform
Component を追加するMonoBehaviour
から Unity.Netcode.NetworkBehaviour
に変更し、一部変更するusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove_KB : Unity.Netcode.NetworkBehaviour
{
private float speed = 1.0f;
private Vector3 moveInput;
void Update()
{
if(this.IsOwner){
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
moveInput = new Vector3(x, 0, z);
Move();
// 復帰処理
if(transform.position.y < -10)
{
transform.position = new Vector3(Random.Range(-5, 5), 0, Random.Range(-5, 5));
}
}
}
private void Move()
{
var delta = new Vector3(moveInput.x, 0, moveInput.z);
transform.position += delta * speed * Time.deltaTime;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove_KB : Unity.Netcode.NetworkBehaviour
{
private float speed = 1.0f;
private Vector3 moveInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(this.IsOwner){
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
MoveServerRpc(x, z);
}
if(this.IsServer){
Move();
// 復帰処理
if(transform.position.y < -10)
{
transform.position = new Vector3(Random.Range(-5, 5), 0, Random.Range(-5, 5));
}
}
}
[Unity.Netcode.ServerRpc]
private void MoveServerRpc(float x, float z)
{
this.moveInput = new Vector3(x, 0, z);
}
private void Move()
{
var delta = new Vector3(moveInput.x, 0, moveInput.z);
transform.position += delta * speed * Time.deltaTime;
}
}
Player Prefab
に Network Animator
Component を追加するAnimator
には自分自身を設定しておく