当前位置:网站首页>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 .

{
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 .
边栏推荐
- Hands on deep learning pytorch version exercise solution - 3.1 linear regression
- 深度学习入门之线性代数(PyTorch)
- [untitled] numpy learning
- Ind FHL first week
- 6、 Data definition language of MySQL (1)
- [LZY learning notes dive into deep learning] 3.5 image classification dataset fashion MNIST
- 七、MySQL之数据定义语言(二)
- Softmax regression (pytorch)
- Data preprocessing - Data Mining 1
- Hands on deep learning pytorch version exercise solution-3.3 simple implementation of linear regression
猜你喜欢
Training effects of different data sets (yolov5)
Introduction to deep learning linear algebra (pytorch)
Drop out (pytoch)
【SQL】一篇带你掌握SQL数据库的查询与修改相关操作
Judging the connectivity of undirected graphs by the method of similar Union and set search
MySQL reports an error "expression 1 of select list is not in group by claim and contains nonaggre" solution
The story of a 30-year-old tester struggling, even lying flat is extravagant
Entropy method to calculate weight
I really want to be a girl. The first step of programming is to wear women's clothes
Jetson TX2 brush machine
随机推荐
Binary search method
Pytorch ADDA code learning notes
神经网络入门之模型选择(PyTorch)
Leetcode skimming ---977
Ut2014 supplementary learning notes
Ind FXL first week
An open source OA office automation system
Leetcode skimming ---704
[LZY learning notes dive into deep learning] 3.5 image classification dataset fashion MNIST
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow
C project - dormitory management system (1)
Julia1.0
ECMAScript -- "ES6 syntax specification # Day1
[combinatorial mathematics] pigeon's nest principle (simple form of pigeon's nest principle | simple form examples of pigeon's nest principle 1, 2, 3)
Adaptive Propagation Graph Convolutional Network
Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported
Ut2015 learning notes
Leetcode skimming ---1
Leetcode skimming ---10
[untitled]