当前位置:网站首页>Unity learning notes: online game pixel Adventure 1 learning process & error correction experience
Unity learning notes: online game pixel Adventure 1 learning process & error correction experience
2022-07-03 10:41:00 【Thymol blue】
Unity Learning notes : Networking games Pixel Adventure 1 The learning process & Error correction experience 、
Before the school taught some online game programming related content , After learning, I still feel that I won't , But it's important to play online games , Just a few days ago, I got a proper tutorial ,B Standing in the barrage comment area, they spoke highly of it , Use of Photon Technical seniors also recommend , Just recently, the engineering practice project has come to an end , So I decided to take this tutorial to learn .
https://www.bilibili.com/video/BV1rJ411D7VJ?spm_id_from=333.999.0.0
This post is used to record some problems and solutions encountered during my study , Similar to error correction book .
Links to resources used :
https://assetstore.unity.com/packages/2d/characters/pixel-adventure-1-155360
Use of Photon:
https://dashboard.photonengine.com/en-US
1. After the resource package is added to my resources, click on Unity There is no response when opening
Reference link :
https://blog.csdn.net/qq_15020543/article/details/83382527?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2aggregatepagefirst_rank_ecpm_v1~rank_v31_ecpm-1-83382527-null-null.pc_agg_new_rank&utm_term=%E5%9C%A8unity%E5%95%86%E5%BA%97%E6%89%93%E5%BC%80%E8%B5%84%E6%BA%90%E6%B2%A1%E5%8F%8D%E5%BA%94&spm=1000.2123.3001.4430
But I just use Hub, So it doesn't help me .
In the end I Created a new blank project , When you open it, you will find that your own resources can appear automatically :
Click on the bottom right corner , Import the resource package after downloading :
( By the way, this seems to be what our engineering practice teacher mentioned Unity new Package Mode or something ? I can't remember clearly )
2. binding App ID To Pun 2

Create your own project AppID Copy down , Paste into import Photon2 In the window that appears later .


Setting Just write a number for the version number here 1
Adjust the category of information display , Want to display all the information , Such as network connection 
Tutorials can be found here :
3. Import

If you can't drag and drop to add an observation , Add the corresponding script manually 
Trigger To put in the last option 
Enter a room to generate a player , So players need to make Prefab, If networking is needed , that Prefab To add to Photon In the folder .
4. The page appears error Unable to load properly
Webpage Bug, hold error Just delete it 

You can enter.
The first episode uses C# Code :
Build an empty object and rename it NetWorkLauncher, Then attach this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class Launcher : MonoBehaviourPunCallbacks// Inherit this class to get feedback from the server
{
// Start is called before the first frame update
void Start()
{
PhotonNetwork.ConnectUsingSettings();// Link server
}
public override void OnConnectedToMaster()// Whether to connect to the game hall , master server
{
base.OnConnectedToMaster();
Debug.Log(" Successful connection !");
// All players entering the same room will be shown on one screen
PhotonNetwork.JoinOrCreateRoom("Room", new Photon.Realtime.RoomOptions() {
MaxPlayers = 4 }, default);
//MaxPlayer Maximum 20 individual ,default It can be changed to other room properties
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
PhotonNetwork.Instantiate("Player", new Vector3(1, 1, 0), Quaternion.identity, 0);
}
// Update is called once per frame
void Update()
{
}
}
Hang on Player Body code ( Only network related functions , No player moves or turns around )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
/// <summary>
/// This script is used to control the movement of players
/// </summary>
public class PlayerMovement : MonoBehaviourPun
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(!photonView.IsMine&&PhotonNetwork.IsConnected)// If the observed role is the current client and the server is running, continue on the contrary return
{
return;
}
}
}
After hanging up these two scripts , It should be able to automatically generate players and Build Settings The windows are synchronized with the players in the run mode windows
5. Report errors Can not Instantiate before the client joined/created a room. State: ConnectedToMasterServer

After reviewing the video , A function binding error was found to create a room , Tied into the script that should have been deleted at the beginning of the second episode ( incidentally , You may not delete the script , Just delete the object with this script )
Change to a new one JoinOrCreateRoom after , Problem solving 
There is no wrong report .
The previous error was reported because this button called the function in the removed script , Equivalent to invalid click , Naturally, no room was created , So wrong reporting Can not Instantiate before the client joined/created a room. State: ConnectedToMasterServer
6. When the roles are reversed , The names on the characters also flip

obtain Sprite Renderer Component's Flip Parameters can be , Don't use your own code
Because I didn't write such perfect code as the teacher , I don't know how to define some variables here , Just fill in the frame .
Looking at the barrage, someone said that it was written because there was no Photon View Sprite Renderer, Therefore, synchronization may not be possible
I tried to find a way to View Sprite Renderer Script for , But it didn't find , I went to Baidu again , No suitable answer has been found yet
I found a link written by a codemate very nutritious :
https://blog.csdn.net/ninesnow_c/article/details/106699608
The second episode uses C# Code :
In order not to report a mistake , I put Flip The part of is commented out :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.UI;
/// <summary>
/// This script is used to control the movement of players
/// </summary>
public class PlayerMovement : MonoBehaviourPun
{
public Text nameText;
public SpriteRenderer sprite;
private void Awake()
{
sprite = GetComponent<SpriteRenderer>();
if(photonView.IsMine)// If the observed character is himself , Just give your name to this object
{
nameText.text = PhotonNetwork.NickName;
}
else// Give the name of the Lord to this object , The name of the character is who you see
{
nameText.text = photonView.Owner.NickName;
}
}
public void Flip()// Flip
{
//if(xVelocity<0)
//{
// sprite.flipX = true;
//}
//else if(xVelocity>0)
//{
// sprite.flipX = false;
//}
}
// Update is called once per frame
void Update()
{
if(!photonView.IsMine&&PhotonNetwork.IsConnected)// If the observed role is the current client and the server is running, continue on the contrary return
{
return;
}
}
}
Hang on Level1 The empty object of the scene is renamed GameManager Script on :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class GameManager : MonoBehaviourPunCallbacks
{
public GameObject readyButton;
public void ReadyToPlay()
{
readyButton.SetActive(false);
PhotonNetwork.Instantiate("Player", new Vector3(1, 1, 0), Quaternion.identity, 0);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Hang on Login In the scene NetworkLauncher( Change the name of an empty object ) Script on NetworkLauncher
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class NetworkLauncher : MonoBehaviourPunCallbacks
{
public GameObject loginUI;
public GameObject nameUI;
public InputField roomName;
public InputField playerName;
// Start is called before the first frame update
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
//base.OnConnectedToMaster();
nameUI.SetActive(true);// If connected to the server , Sign in UI It will show
}
public void PlayButton()
{
nameUI.SetActive(false);
PhotonNetwork.NickName = playerName.text;// The name is transmitted to the network
loginUI.SetActive(true);// Enable login UI
}
public void JoinOrCreateButton()
{
// If there is no name , You can't click the button
if(roomName.text.Length<2)
{
return;
}
loginUI.SetActive(false);
RoomOptions options = new RoomOptions {
MaxPlayers = 4 };
PhotonNetwork.JoinOrCreateRoom(roomName.text, options, default);// Join as soon as possible , Create without
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
PhotonNetwork.LoadLevel(1);
}
}
7. Unable to enter the same room
This object is B Put forward by netizens , I haven't met it myself .
modify Fixed Region, Force access to the same server 
Fill in the code of the country with the fastest Internet speed in the red box at the bottom of the figure Fixed Region, This will ensure that all clients enter the server 
8.Ctrl+ Click to view method details

9. Specify the position to generate the prefab and set the parent object
This code is of reference value , I haven't been able to write this before , Now when you encounter it, you write it down :
10. Report errors ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Baidu said this sentence , Most of them are caused by the array out of bounds .
But I checked my little bit of array code carefully , There seems to be no risk of crossing the line ?
And over and over again Build Several times later , There are new errors , yes Player and RoomListNameButton Not dragging the prefab to the script , So instantiation failed , After solving these two problems, all the strange problems disappeared miraculously .
Running effect :
The third episode uses C# Code :
Hang on Login On empty objects in the scene RoomListManager Of , About the script to update the room list :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class RoomListManager : MonoBehaviourPunCallbacks
{
public GameObject roomNamePreb;
public Transform gridLayout;//content
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
for(int i=0;i<gridLayout.childCount;i++)
{
// Remove all rooms
if(gridLayout.GetChild(i).gameObject.GetComponentInChildren<Text>().text==roomList[i].Name)
{
Destroy(gridLayout.GetChild(i).gameObject);// What was removed was UI Button
// The room is empty and needs to be removed
if(roomList[i].PlayerCount==0)
{
roomList.Remove(roomList[i]);// Remove the room
}
}
}
foreach(var room in roomList)// Traverse the room list
{
// object , Location , Rotation Angle
GameObject newRoom = Instantiate(roomNamePreb, gridLayout.position, Quaternion.identity);
// On the button Text Change to the room name
newRoom.GetComponentInChildren<Text>().text = room.Name +"("+room.PlayerCount+" people )";// Free to DIY Information to be displayed in the room
// The parent object of the generated prefab is set to Content
newRoom.transform.SetParent(gridLayout);
}
}
}
Hang in the action of the protagonist , Responsible for the protagonist position synchronization and protagonist movement ( Didn't write , You can add code such as the left and right movement of the protagonist as needed ):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.UI;
/// <summary>
/// This script is used to control the movement of players
/// </summary>
public class PlayerMovement : MonoBehaviourPun
{
public Text nameText;
public SpriteRenderer sprite;
private void Awake()
{
sprite = GetComponent<SpriteRenderer>();
if(photonView.IsMine)// If the observed character is himself , Just give your name to this object
{
nameText.text = PhotonNetwork.NickName;
}
else// Give the name of the Lord to this object , The name of the character is who you see
{
nameText.text = photonView.Owner.NickName;
}
}
public void Flip()// Flip
{
//if(xVelocity<0)
//{
// sprite.flipX = true;
//}
//else if(xVelocity>0)
//{
// sprite.flipX = false;
//}
}
// Update is called once per frame
void Update()
{
if(!photonView.IsMine&&PhotonNetwork.IsConnected)// If the observed role is the current client and the server is running, continue on the contrary return
{
return;
}
}
}
Hang on Level1 Empty objects in the scene GameManager The script on me GameManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class GameManager : MonoBehaviourPunCallbacks
{
public GameObject readyButton;
public void ReadyToPlay()
{
readyButton.SetActive(false);
PhotonNetwork.Instantiate("Player", new Vector3(1, 1, 0), Quaternion.identity, 0);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Hang on Login On the scene NetworkLauncher Script on :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class NetworkLauncher : MonoBehaviourPunCallbacks
{
public GameObject loginUI;
public GameObject nameUI;
public InputField roomName;
public InputField playerName;
public GameObject roomListUI;
// Start is called before the first frame update
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
//base.OnConnectedToMaster();
nameUI.SetActive(true);// If connected to the server , Sign in UI It will show
Debug.Log("Connecter to the Master");
PhotonNetwork.JoinLobby();// Join the game hall , In this way, you can read RoomList
}
public void PlayButton()
{
nameUI.SetActive(false);
PhotonNetwork.NickName = playerName.text;// The name is transmitted to the network
loginUI.SetActive(true);// Enable login UI
// If you join the hall , The list is displayed UI
if(PhotonNetwork.InLobby)
{
roomListUI.SetActive(true);
}
}
public void JoinOrCreateButton()
{
// If there is no name , You can't click the button
if(roomName.text.Length<2)
{
return;
}
loginUI.SetActive(false);
RoomOptions options = new RoomOptions {
MaxPlayers = 4 };
PhotonNetwork.JoinOrCreateRoom(roomName.text, options, default);// Join as soon as possible , Create without
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
PhotonNetwork.LoadLevel(1);
}
}
The hierarchical relationship is shown in the figure :
Login scene :


UI Hierarchy :
Level1 scene :

I will also upload the complete project CSDN Space , Very brief , There are no other functions besides those I mentioned .
边栏推荐
- 安装yolov3(Anaconda)
- [combinatorial mathematics] pigeon's nest principle (simple form of pigeon's nest principle | simple form examples of pigeon's nest principle 1, 2, 3)
- [LZY learning notes dive into deep learning] 3.5 image classification dataset fashion MNIST
- Codeup: word replacement
- Leetcode skimming ---367
- I really want to be a girl. The first step of programming is to wear women's clothes
- 深度学习入门之线性回归(PyTorch)
- [LZY learning notes dive into deep learning] 3.4 3.6 3.7 softmax principle and Implementation
- Entropy method to calculate weight
- Leetcode刷题---10
猜你喜欢

Entropy method to calculate weight

Ut2012 learning notes

Hands on deep learning pytorch version exercise solution - 2.4 calculus

Class-Variant Margin Normalized Softmax Loss for Deep Face Recognition

8、 Transaction control language of MySQL

Data preprocessing - Data Mining 1

神经网络入门之预备知识(PyTorch)

Hands on deep learning pytorch version exercise solution - 3.1 linear regression

Multi-Task Feature Learning for Knowledge Graph Enhanced Recommendation

Simple real-time gesture recognition based on OpenCV (including code)
随机推荐
[LZY learning notes dive into deep learning] 3.1-3.3 principle and implementation of linear regression
Hands on deep learning pytorch version exercise answer - 2.2 preliminary knowledge / data preprocessing
Out of the box high color background system
The imitation of jd.com e-commerce project is coming
八、MySQL之事务控制语言
Leetcode刷题---10
Leetcode skimming ---263
二分查找法
Raspberry pie 4B installs yolov5 to achieve real-time target detection
Leetcode刷题---44
侯捷——STL源码剖析 笔记
[untitled] numpy learning
Leetcode刷题---35
2018 Lenovo y7000 black apple external display scheme
丢弃法Dropout(Pytorch)
Data preprocessing - Data Mining 1
Install yolov3 (Anaconda)
Leetcode刷题---374
Pytoch has been installed, but vs code still displays no module named 'torch‘
Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported