001 game preview and introduction
Career choice
Mouse click Move rotate zoom
Drug equipment task NPC
State equipment skill Archive
002 import scene resources and build scenes
Third party resources: RPG NGUI StandarAssets
Turn off auto generation
(problem) model map missing
Change the Shader type (so many, one by one), and then drag the map again. Original type Toon/Basic
(problem) the terrain map resource is missing
paint texture remove redraw
The redrawn map is blurred and the normals are wrong
The map is gray
The Terrain data file is missing. Do it again. It is already the official initial document
The second possibility is in the lighting setting. Opened the fog
(problem) Texture Paint doesn't work
The Texture on the surface still can't be painted
Unity 3d, the reason why you can't brush texture on the terrain
(understand) the Tree tab of Terrain
The Tree tab is written into the Terrain, unlike dragging it directly into the scene
The brush size should be larger than the tree density, which can reflect random sparse and not too neat
003 add light to the scene and set the mouse pointer picture
(understand) default mouse
004 add water and sky boxes to the scene
Sky box skyBox
005 achieve the effect of slow zoom in of the lens
Edit / lighting settings not found
Move to window / render / render settings (rendering or lighting)‘
006 use NGUI and white pictures to add fade effects to the scene
NGUI toolbar has only text
NGUI version corresponding to unity 2018.4.32f1
NGUI Next-Gen UI v3.12.1 (Jun 29, 2018)
In one case, I created a new folder to save all the Assets, and then re exported to the root directory.
Atlas Atlas
Here is the addition of the Button picture of NGUI. To add the picture to the atlas, the atlas is required.
Open NGUI / atlas editor
(problem) new failed
unity nGUI atlas saves the file in the project resource folder
(understand)
Compared with the available atlas, there are two attributes: material and texture
(feasible) new = = copy first and then modify
Compared with the available atlas, it is possible to generate mat .png .prefab file.
So try to copy these three and modify them. (feasible)
The storage location is generally the same as the resource folder
Delete
Click X and then delete. Delete multiple points multiple times x, and delete only needs to be clicked once
007 design start interface, start loading buttons and logo s
(button) NRPG button = = Sprite + trigger + UIButton
The trigger size is 0 by default. It should be as large as the button
(button display hidden)
It is said that Tag is used to add objects, but it is wasteful. Direct public
. SetActive uppercase
Press the button to load the game at the beginning, but you want to display it after the animation. Add a timer at the beginning
{ time -= Time.deltaTime; if (Input.anyKeyDown && time<=0)//Because there is an animation at the beginning, time seconds later { newGameButton.SetActive(true); loadGameButton.SetActive(true); pressAnyKey.SetActive(false); } }
PlayerPrefs
PlayerPrefs comes with the system and stores key value pairs in it
void OnNewGame()//Start the game { PlayerPrefs.SetInt("LoadFrom", 0); } void OnLoadGame()//Load game { PlayerPrefs.SetInt("LoadFrom", 1); }
(button sound) AudioSource has no sound
inspect
Audio file (play in folder)
Restart the software
AudioSource fork out and add it again
There are also the following:
ProjectSetting (forgot what to see, volume not 0?)
Game Mute (Mute off)
Component Mute (Mute off)
Component volume (maximum)
011 start role creation scene and import model and UI resources
Import Moedl
Import and add the UI selected by the role to the RPG Atlas (open the atlas, select the UI and click Add/Update)
NGUI button click is invalid
Set the camera type of UIRoot to UI
The NGUI toolbar cannot be dragged out, and many sample scenarios are damaged
Look at the example scenarios 1, 2, 7, 9, 10, 12, 13, 14, 15 and tutorial are all bad
(failed) reboot
The scene is restored, but the toolbar still can't drag anything out
(failed) replace NGUI version
My unit is 2018.4.32f1
The unusable NGUI is NGUI next gen UI v3 twelve point one
The NGUI available is NGUI next gen UI v3 eleven point two
The NGUI that can be used is also a little abnormal, and the style is abnormal
(solved) it disappeared after a while
I found that as long as I update the RPG resources generated by myself, there must be NGUI errors, that is, the two conflict.
Then look at the figure below. If there are trim and replace, cancel them all and try to solve the problem temporarily
One folder and one atlas. Don't cross folders. (maybe this is the reason)
Put NGUI in the root directory Assets (I'd like to put it with other imported resources)
The input box of NGUI coexists with others, and PrefabTool can also drag and drop
Atlas must have 3 files, only 2
Prefab mat missing png
We should look it up from the information Drag the png picture in. Or reboot
After deleting NGUI, the atlas previously made through NGUI's Atlas editor is damaged
add texture again
(an error is reported during import)
Shader error in 'Transparent/Refractive': Too many texture interpolators would be used for ForwardBase pass (9 out of max 8), try adding #pragma target 3.0 at line 41
It's true that there's no error, but it's not used
Unity shader error: "Too many texture interpolators would be used for ForwardBase pass"
Camera for UI and scene
Separate photos are merged and displayed on the screen
Light up at 3 o'clock
Material standard
015 control the selection of previous and next roles
To switch roles, hang on the button
I want to read the file, that is, I use the folder as a component (but I haven't learned how to change the data in the folder directly in computer games)
public GameObject[] characterPrefabArray; public int index=0;//Look private GameObject[] goArray; // Start is called before the first frame update void Start() { if (characterPrefabArray.Length != 0) { //Instance hiding goArray = new GameObject[characterPrefabArray.Length]; for (int i = 0; i < characterPrefabArray.Length; i++) { goArray[i] = Instantiate(characterPrefabArray[i], transform.position, transform.rotation); goArray[i].SetActive(false); goArray[i].transform.parent = transform; } goArray[0].SetActive(true); } } public void PreCharacter() { goArray[index].SetActive(false); index = index == 0 ? (characterPrefabArray.Length - 1) : --index; goArray[index].SetActive(true); } public void NextCharacter() { goArray[index].SetActive(false); index = index == characterPrefabArray.Length - 1 ? 0 : ++index; goArray[index].SetActive(true); }
016 process name input and scene switching
(problem) the input box (UIInput) of NGUI caused by 2D box trigger cannot be clicked for input
Problem description
Up and down, selection buttons can be moved, only the input box can not be clicked
Process introduction
Section A hangs A UIInput node to receive the input box Label;
Node A is referenced by the script. Use value to get the string and store it in PlayerPrefs
Troubleshooting
Node A is UIRoot. There is no problem. There is A problem with the root node of the input box (not in other scenarios).
Factor: the Depth of UIRoot and input box root node is 0 and Label is 1, which are the same
Factor: collider. The result is the problem of box trigger. 2D box trigger should be selected
Factor: in this case, the submit can be omitted
Factor: after running, the UIInput on GUI script will be automatically added to the UIInput node
public void LoadScene() { PlayerPrefs.SetString("SelectedPlayerName", characterNameInput.value); PlayerPrefs.SetInt("SelectedPlayerIndex", index); print(PlayerPrefs.GetInt("SelectedPlayerIndex")); print(PlayerPrefs.GetString("SelectedPlayerName")); SceneManager.LoadScene(2);//2 is data, which should be separated, but I haven't learned it yet }
(understand) invalid texture used for cursor - check importer settings or texture creation Texture must be RGBA32, readable, have alphaIsTransparency enabled and have no mip chain.
I changed it and it disappeared
Invalid texture used for cursor - check importer settings or texture creation. Texture must be RGBA3
(situation) save the unit with an asterisk, without any error or warning
(problem) the NGUI layer is black, and there is nothing after running
Modify the camera culling mask of NGUI and select Default or everything (default also works)
(understand) depth, what is in depth will be illuminated
018 label management
With the following file, Tags Group "group", and there is a prompt after typing Tags (Tags.p may have a prompt for Tags.player)
The advantage is: write fast and don't make mistakes
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tags : MonoBehaviour { public const string group = "Group"; public const string player = "Player"; }
019 realize the click effect of character walking
void Update() { if (Input.GetMouseButtonDown(0)) { print("click"); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//Point generated ray RaycastHit hit; bool isCollided = Physics.Raycast(ray, out hit);//Did you encounter it if (isCollided && hit.collider.tag==Tags.ground) { OnClickEffect(effectPrefab, hit.point); } } } void OnClickEffect(GameObject effectPrefab, Vector3 position) { print("Move"); Instantiate(effectPrefab, position, Quaternion.identity); }
(problem) empty reference
Label for MainCamera
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition) will report an error null reference
(problem) location
Not hit collider. transfrom. Position, but hit point
020 control the direction of the protagonist's movement
(problem) when you click the mouse, you can't reach the goal that the player will always face the position when the mouse is pressed and slid
Video time
Click under the mouse, isMoving=true
Mouse up, isMoving=false
The process from clicking the mouse down to lifting the mouse up is that when the mouse is pressed all the time, this process isMoving=true
In this way, the next click is pressed, the orientation is updated, and the lift is not updated
The consequence of the above is that the Update instance is too many times, and the time is timed when pressing the mouse
void Update() { if (Input.GetMouseButtonDown(0))//Mouse down point { notMouseButtonUp = true; targetPosition = positionByRay2Tag(Input.mousePosition, Tags.ground); prefabByPosition(effectPrefab, targetPosition); } else if (Input.GetMouseButtonUp(0))//Mouse up { notMouseButtonUp = false; } if (notMouseButtonUp)//Press the mouse { targetPosition = targetPosition = positionByRay2Tag(Input.mousePosition, Tags.ground); gameObject.transform.LookAt(targetPosition); //Timing 1 second instance mouseButtonEffectTimer += Time.deltaTime; if (mouseButtonEffectTimer > mouseButtonEffectTime) { mouseButtonEffectTimer = 0f; prefabByPosition(effectPrefab, targetPosition); } } } //Judge whether the ray emitted by mouseDownPosition hits the object labeled tag. Yes, return to the hit position Vector3 positionByRay2Tag(Vector3 mouseDownPosition, string tag) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//Point generated ray RaycastHit hit; bool isCollided = Physics.Raycast(ray, out hit);//Did you encounter it if (isCollided && hit.collider.tag == Tags.ground) { targetPosition = hit.point; return hit.point; } return Vector3.zero;//Default value } void prefabByPosition(GameObject prefab, Vector3 position)//In this position, the prefabricated body is taken as an example { Instantiate(prefab, position, Quaternion.identity); }
021 control the movement of the protagonist
transform.Translate(Time.deltaTime * speed)
void Move() { float stopDistanceNearTargetPosition = 0.2f;//Distance to stop float distance = Vector3.Distance(transform.position, targetPosition); if (targetPosition != Vector3.zero && distance > stopDistanceNearTargetPosition) { transform.Translate(Vector3.forward * Time.deltaTime * speed); } }
Character controller SimpleMove(speed)
void MoveByCharacterController() { float stopDistanceNearTargetPosition = 0.2f;//Distance to stop float distance = Vector3.Distance(transform.position, targetPosition); if (targetPosition != Vector3.zero && distance > stopDistanceNearTargetPosition) { characterController.SimpleMove(transform.forward * speed); } }
022 controls the playback of the protagonist's moving animation
void Update() { if (!MoveByMouse._instance.notMouseButtonUp) { animation.CrossFade("Sword-Idle"); } else if (MoveByMouse._instance.notMouseButtonUp) { animation.CrossFade("Sword-Run"); } }
(problem) players will run head to ground
Y is the player's y
gameObject.transform.LookAt(new Vector3(targetPosition.x, transform.position.y, targetPosition.z) );
(problem) press the mouse to appear run
Because it is based on the mouse state, not vetor3 Distance
(understand) LateUpdate
Update settings status
LateUpdate animating
(code, understand) definition
public enum State { Idle, Walk, Run }
The public of enumeration variables will have the style of drop-down items
(code) setting status
void MoveByCharacterController() { float stopDistanceNearTargetPosition = 0.2f;//Distance to stop float distance = Vector3.Distance(transform.position, targetPosition); if (targetPosition != Vector3.zero && distance > stopDistanceNearTargetPosition) { state = State.Run; characterController.SimpleMove(transform.forward * speed); } else { state = State.Idle; } }
(code) animate based on status
private new Animation animation; private State state = State.Idle; private MoveByMouse player; // Start is called before the first frame update void Start() { animation = GetComponent<Animation>(); player = GetComponent<MoveByMouse>(); } // Update is called once per frame void LateUpdate() { if (player.state==State.Idle) { animation.CrossFade("Sword-Idle"); } else if (player.state == State.Run) { animation.CrossFade("Sword-Run"); } }
023 fix bug s and improve the protagonist's mobile control
(question) after clicking, go straight ahead, mainly in rugged terrain
In particular, the y value is too high, resulting in the distance not reaching all the time. In this case, the player keeps going forward
(problem) feet hanging in the air
025 use the mouse to control the zoom in and zoom out of the camera field of view
code
public GameObject player; private Vector3 offset; //zoom in public float scrollSpeed = 10f;//Stretching speed public float distance;//Actual stretch public float minDistance=3.2f;//Maximum stretch public float maxDistance=30f;//Minimum stretch // Use this for initialization void Start () { offset = transform.position - player.transform.position; //offset = new Vector3(0, offset.y, offset.z);//x=0, no left-right offset } // Update is called once per frame void Update () { transform.position =player.transform.position+ offset; transform.LookAt(player.transform.position); offset = ScrollView(); } Vector3 ScrollView()//Camera stretch { distance = offset.magnitude; distance += scrollSpeed * Input.GetAxis("Mouse ScrollWheel"); if (distance < minDistance) { distance = minDistance; } else if (distance > maxDistance) { distance = maxDistance; } offset = offset.normalized * distance; return offset; }
(understand) Clamp clamping
distance = Mathf.Clamp(distance, minDistance, maxDistance); //Replace the following if (distance < minDistance) { distance = minDistance; } else if (distance > maxDistance) { distance = maxDistance; }
027 controls the left and right rotation of the field of view
(understand) rotation affects the position of the camera and the offset changes
void RotateView() { if (Input.GetMouseButtonDown(1)) { isRotate = true; } if (Input.GetMouseButtonUp(1)) { isRotate = false; } if (isRotate) { transform.RotateAround(player.transform.position, Vector3.up, rotateSpeed*Input.GetAxis("Mouse X")); } offset = transform.position - player.transform.position;//Rotation affects the position of the camera and the offset changes }
028 controls the up and down rotation and range limit of the field of view
code
Press and hold the right mouse button to rotate and clamp up and down (10, 80)
Value should be recorded before RotateAround
void RotateView()//Camera rotation { if (Input.GetMouseButtonDown(1)) { isRotate = true; } if (Input.GetMouseButtonUp(1)) { isRotate = false; } if (isRotate) { //record Vector3 originalPosition = transform.position; Quaternion originalRotation = transform.rotation; //assignment transform.RotateAround(player.transform.position, transform.up, rotateSpeed * Input.GetAxis("Mouse X")); transform.RotateAround(player.transform.position, transform.right, rotateSpeed * Input.GetAxis("Mouse Y")); transform.RotateAround(player.transform.position, transform.right, rotateSpeed * Input.GetAxis("Mouse Y")); //Limit scope if (transform.eulerAngles.x < 10 || transform.eulerAngles.x > 80) { print ("It's out of range"); transform.position = originalPosition; transform.rotation = originalRotation; } } offset = transform.position - player.transform.position;//Rotation affects the position of the camera and the offset changes }
030 add the NPC of grandpa in the scene
(problem) the material of the model is missing and is pink
The type of the material is standard
031 background of design task dialog box
(problem, serious) atlas information is lost, so it needs to be added again
Lost once, especially those with buttons. It's troublesome to add pictures
It is found that the original scene is not broken, but it is not clear why the current scene is broken
Ghosting
About perspective
oil
(problem) wrong position
In the scene, the transfrom is 680 to 150, which can achieve the effect
Tween, it's 700 to - 1410 to reach the desired position
032 task system - contents of design tasks
(problem) Label is not displayed under the unity font
Add a font to the Material material to display the black font, then None, and white, which is displayed normally
It feels like giving NGUI tips. Use fonts quickly
(problem) multiple panels
There is only one normal one (and I have only one). Now, after running, there is one on the left that doesn't move, and the one on the right is from Tween Position
(problem) the image of Terrain appears on the NGUI layer
Too long to shine on the back
Adjust the distance of the camera
Near minimum 0 far minimum 0.01
(understand) the icon in the scene is too large
Unity3D NGUI foundation 2: using NGUI
(understand) the components required for the button
The button of NGUI is equal to Sprite + UIButton + Play Sound + 2D trigger (depending on whether the camera is 2D or 3D, the system automatically switches)
The (solution) button cannot be clicked
The trigger size defaults to 0 and is not adjusted
Automatic spreading with attackh
(understand) GUI layer component deprecation
unity3d 2018.3.10f1 cannot use GUI layer
(problem) the coordinates of NGUI are inconsistent
The character board in the scene ranges from x610 to x250
NGUI only displays 1 / 3, and only x610 to x-770 have the same effect
Look at other videos. The unit of unity is meters, but here the unit is pixels
The distance above is 3601380, that is, 1m = = 2 pixels?
(solution) the NGUI button cannot be clicked
After a lot of comparison, it is most convenient to delete the new one
(solution) uicamera After hoveredobject = = null, click the ground and the character will not move
private void MouseDownEvent() { // if (UICamera.hoveredObject != null) return; if (UICamera.isOverUI) return; print("Mouse down:" + UICamera.hoveredObject); isMouseButtonPress= true; targetPosition = GetTargetPosition(Input.mousePosition); Instantiate(effectPrefab, targetPosition, Quaternion.identity); }
33 click NPC to pop up the task board
The script is attached to NPC. I originally wanted to attach the task board, and I should attach the task board later
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Quest : MonoBehaviour { public GameObject quest; private void OnMouseOver() { if (Input.GetMouseButtonDown(0)) { print("click"); ShowQuest(); } } void ShowQuest() { quest.GetComponent<TweenPosition>().PlayForward(); } public void DisableQuest() { quest.GetComponent<TweenPosition>().PlayReverse(); } }
36 mouse pointer management system
Picture, focus, software and hardware
Method must be called, otherwise
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameSettings : MonoBehaviour { public Texture2D attackCursor; public Texture2D lockTargetCursor; public Texture2D normalCursor; public Texture2D npcTalkCursor; public Texture2D pickCursor; public static GameSettings _instance; private void Awake() { _instance = this; } public void SetNormalCursor() { Cursor.SetCursor(normalCursor, Vector2.zero, CursorMode.Auto );//Graphics, focus } public void SetLockTargetCursor() { Cursor.SetCursor(lockTargetCursor, Vector2.zero, CursorMode.Auto);//Graphics, focus } public void SetAttackCursor() { Cursor.SetCursor(attackCursor, Vector2.zero, CursorMode.Auto);//Graphics, focus } public void SetNpcTalkCursor() { Cursor.SetCursor(npcTalkCursor, Vector2.zero, CursorMode.Auto);//Graphics, focus } public void SetPickCursorr() { Cursor.SetCursor(pickCursor, Vector2.zero, CursorMode.Auto);//Graphics, focus } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Npc : MonoBehaviour { private void OnMouseEnter() { GameSettings._instance.SetLockTargetCursor(); } private void OnMouseExit() { GameSettings._instance.SetNormalCursor(); } }
(understand) scripts have default settings
037 development function panel
01 players click the button on the Bar
02 triggered the function on the total node to open the panel
public void OnStatusButtonClick() { StatusPannel._instance.ShowWindow(); } public void OnBagButtonClick() { BagPannel._instance.ShowWindow(); } public void OnEquipmentButtonClick() { EquipPannel._instance.ShowWindow(); } public void OnSkillButtonClick() { SkillPannel._instance.ShowWindow(); } public void OnSettingButtonClick() { SettingPannel._instance.ShowWindow(); }
03 call the parent method ShowWindow of the corresponding panel
public class Pannel : MonoBehaviour { [Tooltip("Parent class Window The field of is not set, but can be called")] public bool isShow = false; [Tooltip("close Pannel Button for")] public UIButton closeButton; public void ShowWindow() { GetComponent<TweenPosition>().PlayForward(); isShow = true; } public void DisableWindow() { GetComponent<TweenPosition>().PlayReverse(); isShow = false; } }
39-49 backpack system
TextAsset read txt
flow chart
Data text
1001, vial blood drug, icon-potion1, position, 50,0,50,60
1002, large bottle of blood medicine, icon-potion2, potion100,0,70100
1003, blue medicine, icon-potion3, position, 100,60,80
2001, golden armour, armor0 icon, equip, 0,50,0, armor, swardman, 150200
2002, copper armour, armor1 icon, equip, 0,39,0, armor, swardman, 100150
2003, miracle magic suit, armor2 icon, equip, 0,50,0, armor, magician, 150200
2004, worn magic suit, armor3 icon, equip, 0,20,0, armor, magician, 60100
2005, copper shoes, icon boot0, equip, 0,0,50, shoe, common, 60100
2006, divine red shoes, icon-boot0-01, equip, 0,0,70, shoe, common, 120150
2007, hat, icon helm, equip, 0,50,0, headgear, swordman, 100120
2008, God hat, icon-helm-01, equip, 0,70,0, headgear, swordman, 120200
2009, divine magic hat, icon-helm-02, equip, 0,70,0, headgear, magician, 120200
2010, ordinary magic hat, icon-helm-03, equip, 0,50,0, headgear, magician, 100120
2011, gold ring, icon ring, equity, 0,50,0, accessory, common, 50,70
2012, turquoise ring, icon-ring-01,Equip,0,30,0,Accessory,Common,30,50
2013, shield, icon shield, equity, 0,50,0, lefthand, common, 50,70
2014, aegis, icon shield 1, equip, 0,70,0, lefthand, common, 70100
2015, Royal necklace, icon tailman, equip, 0,30,0, accessory, common, 30,60
2016, matchstick, rod icon, equip, 40,0,0, righthand, magician, 40,80
2017, metal stick, rod-icon02, equip, 60,0,0, righthand, magician, 60120
2018, divine magic wand, rod-icon03, equip, 80,0,0, righthand, magician, 80200
2019, Yujian, sword0 icon, equip, 40,0,0, righthand, swordman, 40,60
2020, two handed sword, sword0 icon00, equip, 60,0,0, righthand, swordman, 60100
2021, white Emperor holy sword, sword1 icon, equip, 80,0,0, righthand, swordman, 80150
2022, the first sword of China, sword2 icon, equip, 100,0,0, righthand, swordman, 150200
(code) model class
Without monobehavior, the following subclasses cannot be displayed in the editor
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item:MonoBehaviour//Item information { public int id;//000 public new string name; public string icon_name; public ItemType itemType; public int price_sell; public int price_buy;//5 public DressType dressType;//position public ApplyType applyType;//occupation public int attack; public int defense; public int speed; public int hp; public int mp; void Start() { } } public enum ItemType//Type of article { Potion, Equip, Mat, Undefined }
(code) convert TextAsset to List
The functions of the two methods are
1. Read TextAsset and write Dictionary
2. Read the Dictionary and return an object of the above model class
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TextAssetToDictionary: MonoBehaviour { [Tooltip("Data text, English comma segmentation, carriage return, line feed")] public TextAsset textAsset; [Tooltip("The component is not displayed to allow access to the call")] public Dictionary<int, Item> dictionary = new Dictionary<int, Item>(); public static TextAssetToDictionary _instance; void Awake() { _instance = this; dictionary = Read(textAsset); } public Dictionary<int, Item> Read(TextAsset textAsset)//Read TextAsset and store it in Dictionary { string[] lineArray = textAsset.text.Split('\n'); foreach (string line in lineArray) { string[] propertyArray = line.Split(',');//English comma //shunt Item item = new Item(); item.id = int.Parse(propertyArray[0]); item.name = propertyArray[1]; item.icon_name = propertyArray[2]; //Assign values in specific fields according to types switch (propertyArray[3]) { case "Potion": item.itemType = ItemType.Potion; break; case "Equip": item.itemType = ItemType.Equip; break; case "Mat": item.itemType = ItemType.Mat; break; default: item.itemType = ItemType.Undefined; break; } //drugs switch (item.itemType) { case ItemType.Potion://drugs { item.hp = int.Parse(propertyArray[4]); item.mp = int.Parse(propertyArray[5]); item.price_sell = int.Parse(propertyArray[6]); item.price_buy = int.Parse(propertyArray[7]); } break; case ItemType.Equip://equipment { item.attack = int.Parse(propertyArray[4]); item.defense = int.Parse(propertyArray[5]); item.speed = int.Parse(propertyArray[6]); switch (propertyArray[7]) { case "Headgear": item.dressType = DressType.Headgear; break; case "Armor": item.dressType = DressType.Armor; break; case "LeftHand": item.dressType = DressType.LeftHand; break; case "RightHand": item.dressType = DressType.RightHand; break; case "Shoe": item.dressType = DressType.Shoe; break; case "Accessory": item.dressType = DressType.Accessory; break; default: break; } switch (propertyArray[8]) { case "Swordman": item.applyType = ApplyType.Swordman; break; case "Magician": item.applyType = ApplyType.Magician; break; case "Common": item.applyType = ApplyType.Common; break; default:break; } item.price_sell = int.Parse(propertyArray[9]); item.price_buy = int.Parse(propertyArray[10]); } break; default: break; } dictionary.Add(item.id, item); } return dictionary; } public Item GetItemById(int id) { dictionary.TryGetValue(id, out Item item); return item; } }
knapsack
flow chart
Item group is a group of items, which means a pile of items with more attributes;
I wanted to use bag before_ Item, but the same attribute is used in the store
The prefab of the instance is ItemGroup, which inherits from Item. The using... Start Update method of Item cannot be deleted, otherwise it and its subclasses cannot be hung (or displayed) in the editor
(problem) multiple generation
There is a problem with the previously recorded NGUI, that is, dragging the front sometimes (often generates items)
Because you click to generate items. Drag the first one to form a space, so it generates an item in the first place
for (int i = 0; i < gridList.Count; i++) { string itemName= itemList[itemIndex].GetComponent<UISprite>().spriteName; string goodName= gridList[i].childCount ==0 ? "" : gridList[i].GetChild(0).GetComponent<UISprite>().spriteName ; print(goodName+","+itemName);//test bool isFind = (itemName==goodName);//Can you find the same sprite name in the child nodes of the grid if (isFind) { print("identical"); IncreaseGood(i); break; }
(code) get the data and hang it under BagPannel
Pass each item in the dictionary to ItemGroup
void InitItemPrefabList()//Read the text, derive the Item prefab, and generate the object { dictionary = GetComponent<TextAssetToDictionary>().dictionary; print("3423"+dictionary.Count); //Traverse the dictionary, fill in itemPrefab and add it to the list for (int i = 0; i < dictionary.Count; i++) { //Look at the id of the text to change Item item =new Item(); if (i > 2) item = dictionary[2001 + i - 3];//drugs //Value else item = dictionary[1001 + i];//equipment GameObject itemPrefab = Instantiate(bag_Item);//generate itemPrefab.transform.parent = transform;//Hanging under the main node, beautiful itemPrefab = itemPrefab.GetComponent<Bag_Item>().SetValue(item);//assignment itemPrefabList.Add(itemPrefab);//join } }
(code) ItemGroup
According to the Item value and UI display, I vaguely think that the inherited class can be used, but I haven't learned it yet
If you inherit an Item, it will be excluded by Monobehavior, so you can't add it in the editor.
So we still treat Item as a component
(done), that is, the using, start and update of the base class Item cannot be omitted, so that it cannot be dragged to the object
See ScriptableObject and introduce a single video (drag one out and fill in the value). I haven't learned its value for the time being
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemGroup : Item { //More than Item [Tooltip("Information prompt box")] public GameObject tipGo; [Tooltip("Text of message prompt box")] private UILabel tipLabel; [Tooltip("Number of text boxes")] public UILabel countLabel; [Tooltip("quantity")] public int count = 0; [Tooltip("Information prompt box display time")] public float activeTime = 0.2f; [Tooltip("Message box timer")] public float timer = 0f; void Start() { } void Update() { } public void DisableTip()//Information box timing hidden { tipGo.SetActive(false); } public void ShowTip()//Display prompt box text { tipGo.SetActive(true); string tip = ""; switch (itemType) { case ItemType.Potion://drugs { tip = "name:" + name; tip += "\n Type: drug"; tip += "\n effect: Hp+" + hp; tip += "\n effect: Mp+" + mp; tip += "\n Selling price:" +price_sell; } break; case ItemType.Equip://equipment { string dressTypeStr = ""; switch (dressType)//position { case DressType.Headgear:dressTypeStr = "head";break; case DressType.Armor:dressTypeStr = "body";break; case DressType.LeftHand:dressTypeStr = "left hand";break; case DressType.RightHand:dressTypeStr = "one 's right hand";break; case DressType.Shoe:dressTypeStr = "foot";break; case DressType.Accessory:dressTypeStr = "ornaments";break; } string applyTypeStr = ""; switch (applyType)//occupation { case ApplyType.Swordman: applyTypeStr = "warrior"; break; case ApplyType.Magician: applyTypeStr = "magician"; break; case ApplyType.Common: applyTypeStr = "currency"; break; } //Print tip = "name:" + name; tip += "\n Type: equipment"; tip += "\n Location type:"+ dressTypeStr; tip += "\n Occupation type:"+ applyTypeStr; tip += "\n Attack:"+ attack; tip += "\n Defense:"+ defense; tip += "\n Speed:"+ speed; tip += "\n Selling price:" + price_sell; } break; default: { tip = "Name: unnamed"; tip += "\n Type: undefined"; } break; } tipLabel.text = tip; } public void SetValue(Item item)//The data of the parent class is assigned to the child class because the data is of the parent class { id=item.id; name=item.name; icon_name=item.icon_name; itemType=item.itemType; price_sell= item.price_sell; price_buy= item.price_buy; dressType= item.dressType; applyType= item.applyType; attack= item.attack; defense= item.defense; speed = item.speed; hp= item.hp; mp= item.mp; } }
(code) drag and drop components
Rewritten UIDragAndDrop and added it to the item.
The Grid label is Grid and the preform label is Good
using UnityEngine; public class MyDragDrop : UIDragDropItem { [Tooltip("The position of the object to start dragging")] private Vector3 startPos = Vector3.zero; protected override void OnDragDropStart() { base.OnDragDropStart(); startPos = base.transform.position;//Record the start position in order to roll back to the original position } protected override void OnDragDropRelease(GameObject surface) { base.OnDragDropRelease(surface); print(surface.tag); if (surface.tag == "Grid") { //transform.position = surface.transform.position;// Put the object in the grid transform.parent = surface.transform; transform.localPosition = Vector3.zero; } else if (surface.tag == "Good") { //Position exchange transform.position = surface.transform.position; surface.transform.position = startPos; } else//Take it off to the wrong position { transform.position = startPos; } } }
(code) add items and hang them under BagPannel
The total node of the backpack is convenient for prefabrication
void CreateNewItem(List<Transform> gridList,List<Item> itemList)//Click the test function of the generated item, { //1 add an item randomly int createNewItemId = itemList[ Random.Range(0, itemList.Count) ].id;//id of the new item //2 is there the same for (int i = 0; i < gridList.Count; i++)//Find the index of grid with the same picture name { if (gridList[i].transform.childCount == 0)//loop { AddNewItem(i, createNewItemId);//Use the obtained id to the corresponding i instance break; } else if (gridList[i].transform.childCount > 0) { int itemGroupId = gridList[i].transform.GetChild(0).GetComponent<ItemGroup>().id;//Get the ID of the item in the grid, moonobehavior exclusion if (itemGroupId == createNewItemId)//Same, to the corresponding i plus { AddExistingItem(i); break; } else//loop { if (i == gridList.Count - 1) print("Full"); } } } } void AddNewItem(int index,int id)//newly added { Item item= TextAssetToList._instance.GetItemById(id); GameObject go = Instantiate(itemGroupPrefab); ItemGroup itemGroup = go.GetComponent<ItemGroup>(); itemGroup.SetValue(item); go.GetComponent<UISprite>().spriteName = itemGroup.icon_name; go.transform.parent = gridList[index].transform; go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; itemGroupList.Add(item); } void AddExistingItem(int gridIndex)//Old increase { Transform t = gridList[gridIndex].transform;//Respective position int count = int.Parse(t.GetChild(0).GetChild(0).GetComponent<UILabel>().text);//Items under the grid, Label objects under items t.GetChild(0).GetChild(0).GetComponent<UILabel>().text = (++count).ToString(); }
(understand) UI Trigger component
Display and hide mouse hover
Drag over and out into the display hidden information prompt box respectively
(question) the prompt box is not displayed in Chinese
Support Chinese Fonts
(problem) the picture is too large
go.transform.localScale = Vector3.one;
(question) The root GameObject of the opened Prefab has been moved out of the Prefab
Now we just drag it out and change it, and then drag it back
The root GameObject of the opened Prefab has been moved out of the Prefab ...
50-52 status system (allocation, application, reset and modification of attribute points)
flow chart
UI
code
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Status : Window { private int attack ; private int defense; private int speed; private int point; [Tooltip("Digital part Label")] public UILabel attackLabel; [Tooltip("Digital part Label")] public UILabel defenseLabel; [Tooltip("Digital part Label")] public UILabel speedLabel; [Tooltip("Digital part Label")] public UILabel pointLabel; // Start is called before the first frame update void Start() { GetValue(); SetLabel(); } //Click the corresponding add button public void OnAttackClick() { bool havePoint = ConsumePoint(); if (!havePoint) return; attack++; SetLabel(); } public void OnDefenseClick() { bool havePoint = ConsumePoint(); if (!havePoint) return; defense++; SetLabel(); } public void OnSpeedClick() { bool havePoint = ConsumePoint(); if (!havePoint) return; speed++; SetLabel(); } //Deduct if you have enough money, and return true; Otherwise, return false private bool ConsumePoint() { point--; if (point < 0) { point++; return false; } return true; } public void ResetValue ()//Reset { GetValue(); SetLabel(); } public void SetValue()//Apply modification { PlayerStatus._instance.attack=attack; PlayerStatus._instance.defense=defense; PlayerStatus._instance.speed=speed; PlayerStatus._instance.point=point; } public void GetValue()//Get data from players { attack = PlayerStatus._instance.attack; defense = PlayerStatus._instance.defense; speed = PlayerStatus._instance.speed; point = PlayerStatus._instance.point; } public void SetLabel()//Label output to status board { attackLabel.text = attack.ToString(); defenseLabel.text = defense.ToString(); speedLabel.text = speed.ToString(); pointLabel.text = point.ToString(); } }
There is no optional box in front of the problem component
unity – why is the check box in front of the script missing in the Inspector view
After changing the name of a parent class method, the tweetposition is lost
The background is to trigger the method of the parent node of the status button to call the parent method ShowWindow of the status bar
Now try to trigger the method of the parent node of the status button to call the parent method ShowWindow of the status bar, which can achieve the effect
So the problem is the method of the parent node
53-55 store system
56-63 equipment system
The video is worn by clicking on the equipment in the backpack
Yes, on the UI
01 the temporary Bag is on the left and the equipment bar is on the right, which is convenient for dragging and adding equipment
02 interface is not enough to display two panels, so show one and hide one. Double click (right click)
Requirements:
01. Open the equipment bar, click the part, hide the equipment bar, and pop up the backpack bar to display the player's occupation type and the person's equipment of this part type, and then click the equipment to realize the wearer or 02. Replacement, addition and subtraction of player attributes
Open the backpack, pop up the backpack bar, display the player's occupation type and the person's equipment of this part type, and then click the equipment to wear or replace, and add or subtract the player's attributes
03. Realize the separation of data and display in the backpack to facilitate the display of equipment that can be equipped. Stored is
class
There are more count attributes than Item, and groups are a bunch.
Box is the UI display used for prefabrication
technological process
(refactoring) disassemble the data table and object table
In the background, click in the position slot of the equipment bar to enter the backpack. What you want the backpack to display is the items belonging to the equipment of the class
Think of the data in one file. This data can be all types of item table, equipment table, medicine table, equipment boss's commodity table and medicine boss's commodity table.
(code) original
Correspondingly, the number of additions and subtractions also needs to be updated, so it is redundant
void AddNewItem(int index,int id)//newly added { Item item= TextAssetToList._instance.GetItemById(id); GameObject go = Instantiate(itemGroupPrefab); ItemGroup itemGroup = go.GetComponent<ItemGroup>(); itemGroup.SetValue(item); go.GetComponent<UISprite>().spriteName = itemGroup.icon_name; go.transform.parent = gridList[index].transform; go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; itemGroupList.Add(item); }
(code) now, remove the display part for reuse
void AddNewItem(int id)//newly added { Item item= TextAssetToList._instance.GetItemById(id); ItemGroup itemGroup = new ItemGroup(); itemGroup.SetValue(item); itemGroup.count = 1; itemGroupList.Add(itemGroup); } void DisplayItem(List<ItemGroup> itemGroupList)//Get the corresponding data table itemGroupList and instance it { if (itemGroupObjectList!=null) { foreach (GameObject itemGroupObject in itemGroupObjectList) { Destroy(itemGroupObject); } itemGroupObjectList.Clear();//No, there are many Missing objects in the clear list } Re Exhibition for (int i = 0; i < itemGroupList.Count; i++) { GameObject go = Instantiate(itemGroupPrefab); ItemGroup itemGroup = go.GetComponent<ItemGroup>(); itemGroup.SetValue(itemGroupList[i]); itemGroup.countLabel.text = itemGroup.count.ToString(); go.GetComponent<UISprite>().spriteName =itemGroup.icon_name; go.transform.parent = gridList[i].transform; go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; itemGroupObjectList.Add(go); } }
(problem) add the first random item in the first grid dead cycle
The code of the instance is in the Display method. The Display is exposed in the Update instead of the left mouse button.
Nor did it destroy the previous ones
void Update() { if (Input.GetKeyDown(KeyCode.Space) && _instance.isShow)//Click when the backpack is open { CreateNewItem(itemList);//Clone objects into backpacks DisplayItem(itemGroupList); } }
Display again, there is no list of objects before clear
void DisplayItem(List<ItemGroup> itemGroupList)//Get the corresponding data table itemGroupList and instance it { itemGroupObjectList.Clear(); for (int i = 0; i < itemGroupList.Count; i++) { GameObject go = Instantiate(itemGroupPrefab); ItemGroup itemGroup = go.GetComponent<ItemGroup>(); itemGroup.SetValue(itemGroupList[i]); itemGroup.countLabel.text = itemGroup.count.ToString(); go.GetComponent<UISprite>().spriteName =itemGroup.icon_name; go.transform.parent = gridList[i].transform; go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; itemGroupObjectList.Add(go); } }
Click the equipment slot to display the equipment (screening) of the corresponding occupation and position
//Click in from the equipment bar public void OnDressTypeClick(DressType dressType)//Filter out items of class type, Item type (equipment) and part type { List<ItemGroup> equipGroupList = new List<ItemGroup>(); foreach (ItemGroup itemGroup in BagPannel._instance.itemGroupList) { if (itemGroup.dressType == dressType && itemGroup.applyType == Player._instance.applyType && itemGroup.itemType == ItemType.Equip)//Find out the equipment that matches the occupation and position { equipGroupList.Add(itemGroup); } } BagPannel._instance.DisplayItem(equipGroupList); this.DisableWindow(); BagPannel._instance.ShowWindow(); }
Left click equipment, or replace
public void DressEquipItem(ItemGroup itemGroup) { //Replace operation if (itemGroup.itemType != ItemType.Equip ) return; if (itemGroup.applyType != Player._instance.applyType && itemGroup.applyType != ApplyType.Common) return; Transform dressTrans = EquipPannel._instance.DressTypeToTransform(itemGroup.dressType); if (dressTrans.childCount != 0)//Replace, rollback action is added, and others are the same { //Remove UnDressEquipItem(dressTrans.GetChild(0).GetComponent<EquipItem>()); } MinusExistingItem(itemGroup.id);//Reduce or destroy or remove EquipPannel._instance.DressItemGroup(itemGroup);//equipment }
The item preform writing method passes the parameter id to BagPannel and is called by the double-click action
public void OnItemGroupDubleClick() { BagPannel._instance.UseItemGroup(id); }
Take off
public bool UnDressEquipItem(EquipItem equipItem) { print("bag Take off"); if (itemGroupList.Contains(equipItem))//Have the same kind { AddExistingItem(equipItem.id); } if (!itemGroupList.Contains(equipItem))//No similar { if (itemGroupObjectList.Count + 1 > gridList.Count)//It is full and cannot be removed { return false; } AddNewItem(equipItem.id); } return true; } }
The player double clicks the EquipItem to pass the wearing type to the equipment bar
public void UndressItemGroup() { EquipPannel._instance.UndressItemGroup(dressType); }
In the equipment grid, destroy the equipment on the corresponding part according to the wearing type, and roll back (add or add) the equipment to the backpack
public void UndressItemGroup(DressType dressType) { //Destroy, pass id Transform equipTransform; switch (dressType) { case DressType.Headgear: equipTransform = headgear; break; case DressType.Armor: equipTransform = anmor; break; case DressType.LeftHand: equipTransform = leftHand; break; case DressType.RightHand: equipTransform = rightHand; break; case DressType.Shoe: equipTransform = shoe; break; case DressType.Accessory: equipTransform = accessory; break; default: throw new System.Exception("Error removing equipment"); } //Destroy rollback int id = equipTransform.GetChild(0).GetComponent<ItemGroup>().id; Destroy(equipTransform.GetChild(0).gameObject); BagPannel._instance.AddExistingItem(id); }
(problem) InvalidOperationException: Collection was modified; enumeration operation may not execute.
The list was modified while enumerating the list
(problem) text prompt box error
Assign a value to the ontology, not to an object that receives the ontology. The error text box displays the value of the preform
ItemGroup itemGroup = go.GetComponent<ItemGroup>(); itemGroup.SetValue(item); //correct go.GetComponent<ItemGroup>().SetValue(item);
(phenomenon) set the font spacing adjustment value "Microsoft YaHei"
Is too laggy to drag the font of ttf to unity, which is very long.