I don't know how to save a List<T> of items I have and the inventory script and the database items script. I want to save the items that I have in my inventory but I don't know how. I try to create a class and make an Update() function but id doesn't work. It gives me an error
inventory<item> can't be deserialized
Can you help me please how should I save the items?
Here is the script o the player data that contains the save/load functions.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
public class PlayerData : MonoBehaviour {
public int HP,MP,HPMAX,MPMAX,STR,DEF,EXP,LVL;
public Text HPtext,MPtext,STRtext,DEFtext,LVLtext,amountTxt;
public static PlayerData Pdata;
public GameObject player;
public int amount = 20;
public bool UseKey;
public bool poisened;
public float counter = 5;
//==============================================================
public List<Item> Inventory = new List<Item> ();
//==============================================================
public float x,y ;
inventoryTest inv;
void Awake()
{
if(Pdata == null)
{
DontDestroyOnLoad(gameObject);
Pdata = this;
}
else if(Pdata != this)
{
Destroy(gameObject);
}
}
void Start()
{
inv = GameObject.FindWithTag("Player").GetComponent<inventoryTest>();
HP = 20;
MP = 5;
HPMAX = 20;
MPMAX = 5;
STR = 8;
DEF = 8;
EXP = 0;
LVL = 1;
}
void Update()
{
//==========================================
Inventory = inv.Inventory;
//==========================================
amountTxt.text = ""+amount;
HPtext.text = ""+HP;
MPtext.text = ""+MP;
STRtext.text = ""+STR;
DEFtext.text = ""+DEF;
LVLtext.text = ""+LVL;
x = player.transform.position.x;
y = player.transform.position.y;
if(HP > HPMAX){
HP = HPMAX;
}
if(MP > MPMAX){
MP = MPMAX;
}
if(MP <= 0){
MP = 0;
}
if(HP <= 0){
HP = 0;
}
if(amount <= 0){
amount = 0;
}
if(amount >= 99){
amount = 99;
}
if(EXP == 100){
EXP = 0;
LVL++;
STR++;
DEF++;
HPMAX += 10;
MPMAX += 5;
}
if(LVL == 99){
LVL = 99;
}
}
void FixedUpdate(){
if(poisened){
counter -= Time.deltaTime;
if(counter < 0f){
HP -= 1;
counter = 5;
}
}
}
public void Save(){
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/S_F.dat" );
playerDataClass data = new playerDataClass();
data.HP = HPMAX;
data.MP = MPMAX;
data.STR = STR;
data.DEF = DEF;
data.EXP = EXP;
data.LVL = LVL;
data.y = y;
data.x = x;
//====================================
data.Inventory = Inventory;
//====================================
BF.Serialize(file,data);
file.Close();
}
public void Load(){
if(File.Exists(Application.persistentDataPath + "/S_F.dat")){
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/S_F.dat", FileMode.Open);
playerDataClass data = (playerDataClass) BF.Deserialize(file);
file.Close();
HPMAX = data.HPMAX;
MPMAX = data.MPMAX;
HP = data.HP;
MP = data.MP;
STR = data.STR;
DEF = data.DEF;
EXP = data.EXP;
LVL = data.LVL;
x = data.x;
y = data.y;
player.transform.position= new Vector2(x,y);
}
}
}
[Serializable]
public class playerDataClass
{
public int HPMAX,MPMAX,HP,MP,STR,DEF,EXP,LVL;
public float x,y ;
//=======================================================
public List<Item> Inventory = new List<Item> ();
//=======================================================
}
Edit here is he Inventory Script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class inventoryTest : MonoBehaviour {
public Transform panel,MenuPosition,gPanelPosition;
public List<Item> Inventory = new List<Item> ();
public ItemDatabase data;
public Text testText,saveTextl,USEtext,EQUIPtext;
PlayerData Playerdata;
PlayerControl contol;
public Color saveColor;
public bool Eaquiped;
int GeneralMenu = 2;
int optionMenu = 2;
int Index3 = 0;
int Index2 = 0;
int Index = 0;
public float Yoffset;
public Image iconGeneral,iconMini,icon;
public GameObject saveMessage,ave,arrowAmount,gPanel,itemOption,camerA,Menu;
public bool A,B,moveup,movedown,SaveOptionAvalable,openOption,gOption,t,pressed,faceDoor;
void Start(){
contol = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerControl> ();
Playerdata = GameObject.FindGameObjectWithTag ("Playerdata").GetComponent<PlayerData> ();
data = GameObject.FindGameObjectWithTag ("database").GetComponent<ItemDatabase> ();
camerA = GameObject.FindWithTag("MainCamera");
Color colorT = saveColor;
colorT.a = 0.1f;
saveTextl.color = colorT;
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
itemOption.SetActive(false);
saveMessage.SetActive(false);
}
void Update (){
t = true;
if(SaveOptionAvalable){
Color colorT = saveColor;
colorT.a = 1f;
saveTextl.color = colorT;
}else if(!SaveOptionAvalable){
Color colorT = saveColor;
colorT.a = 0.1f;
saveTextl.color = colorT;
}
//====== Menu DESPLAY ==========================================================================================================================
//==for toch cotrole====================================================================================
if (B && !pressed) {
pressed = true;
Menu.transform.position = new Vector2(camerA.transform.position.x,camerA.transform.position.y);
Time.timeScale = 0;
arrowAmount.SetActive(false);
B = !B;
}else if (B && pressed && !openOption && !gOption && !SaveOptionAvalable) {
Time.timeScale = 1;
pressed = !pressed;
Menu.transform.position = new Vector2(MenuPosition.transform.position.x,MenuPosition.transform.position.y);
if(contol.equipbow == true)
{
arrowAmount.SetActive(true);
}
B = !B;
}
else if (B && pressed && openOption){
openOption = !openOption;
itemOption.SetActive(false);
Color colorT = saveColor;
colorT.a = 1f;
USEtext.color = colorT;
EQUIPtext.color = colorT;
B = !B;
}
//====BACK TO GENERAL MENU===============================================================================================================
//=====FOR TOCH CONTROL==============================================================================
if(B && pressed && gOption) {
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
gOption = !gOption;
if(contol.inSaveErea == true){
SaveOptionAvalable = true;
}
else if (contol.inSaveErea == false){
SaveOptionAvalable = false;
}
B = !B;
}
if( A && pressed && !gOption) {
if(Index3 == 0){
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
gOption = true;
Debug.Log(gOption);
SaveOptionAvalable = false;
A =!A;
}
if(Index3 == 1 && SaveOptionAvalable && !gOption){
saveMessage.SetActive(true);
Debug.Log(SaveOptionAvalable);
gOption = true;
A =!A;
}
}
//=====================================================================================================
//==== KEYBOARD CONTROL================================================================================
// if(Input.GetKeyDown (KeyCode.B)&& pressed && gOption ){
// gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
// gOption = !gOption;
// }
// if(Input.GetKeyDown(KeyCode.A) && pressed && !gOption){
// if(Index3 == 0){
// gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
// gOption = true;
// Debug.Log(gOption);
// return;
// }
// if(Index3 == 1 && !SaveOptionAvalable){
// }
// if(Index3 == 2){
// }
// }
//=======================================================================================================================================
//===SAVE BITTON AND SAVE MESSAGE========================================================================================================
//====TOUCH CONTROL===================================================================================================
if(A && pressed && SaveOptionAvalable)
{
saveMessage.SetActive(false);
Playerdata.Save();
Debug.Log("SAVED");
SaveOptionAvalable = !SaveOptionAvalable;
gOption = !gOption;
A = !A;
}
if(B && pressed && SaveOptionAvalable)
{
saveMessage.SetActive(false);
SaveOptionAvalable = true;
SaveOptionAvalable = !SaveOptionAvalable;
Debug.Log("CANCELED");
B = !B;
}
//===KEYBOARD CONTROL==================================================================================================
//=============================================================================================================================
//===UP/DOWN NAVIGATION MENU===================================================================================================
//===TOUCH CONTROL==============================================================
if(movedown && pressed && !gOption && !openOption ){
movedown = !movedown;
if(Index3 < GeneralMenu -1){
Index3++;
Vector2 position = iconGeneral.transform.position;
position.y -= Yoffset;
iconGeneral.transform.position = position;
return;
}
}
if(moveup && pressed && !gOption && !openOption){
moveup = !moveup;
if(Index3 > 0){
Index3--;
Vector2 position = iconGeneral.transform.position;
position.y += Yoffset;
iconGeneral.transform.position = position;
return;
}
}
//=======INVENTORY : Selectig Item With Up and Down Arrows and pressing A to Use and B to Cancel ============================================================================================================================
for(int i = 0 ; i < Inventory.Count; i++){
//===TOUCH CONTROL========================================================================================
if(movedown && pressed){
movedown = !movedown;
if(Index < Inventory.Count -1 && !openOption ){
Index++;
Vector2 position = icon.transform.position;
position.y -= Yoffset;
icon.transform.position = position;
return;
}if(Index2 < optionMenu -1 && openOption){
Index2++;
Vector2 position = iconMini.transform.position;
position.y -= Yoffset;
iconMini.transform.position = position;
return;
}
}
if(moveup && pressed){
moveup = !moveup;
if(Index > 0 && !openOption ){
Index -- ;
Vector2 position = icon.transform.position;
position.y += Yoffset;
icon.transform.position = position;
return;
}if(Index2 > 0 && openOption){
Index2--;
Vector2 position = iconMini.transform.position;
position.y += Yoffset;
iconMini.transform.position = position;
return;
}
}
//===============================================================================================================
//======= USE/EQUIPE MENU ===================================================================================================
//===TOUCH CONTROL===============================================================================================
if(A && pressed && !openOption && gOption && !SaveOptionAvalable){
openOption = true;
itemOption.SetActive(true);
A = !A;
}
if(A && openOption){
openOption = !openOption;
//===== IF PRESS USE TOUCH CONTROL=================================================================================================
if(Index2 == 1)
{
if(Index == i){
if(Inventory[i].ItemId == 5 && contol.equipSword == true && contol.equipbow == false){
contol.equipSword = false;
contol.equipbow = true;
t = false;
var ttt = GameObject.Find("sword").GetComponent<Text>();
ttt.text = "sword" + "";
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
if(Inventory[i].ItemId == 4 && contol.equipSword == false && contol.equipbow == true){
contol.equipSword = true;
contol.equipbow = false;
t = false;
var ttt = GameObject.Find("bow").GetComponent<Text>();
ttt.text = "bow" + "";
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
if(Inventory[i].ItemId == 4 && contol.equipSword == false)
{
contol.equipSword = true;
contol.equipbow = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
else if(Inventory[i].ItemId == 4 && contol.equipSword == true){
contol.equipSword = false;
contol.equipbow = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname;
A =!A;
}
if(Inventory[i].ItemId == 5 && contol.equipbow == false)
{
contol.equipbow = true;
contol.equipSword = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
else if(Inventory[i].ItemId == 5 && contol.equipbow == true){
contol.equipbow = false;
contol.equipSword = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname;
A =!A;
}
if(Inventory[i].ItemId == 0)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 1)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 2)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 3)
{
if(!faceDoor){
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
}
}
openOption = true;
}
if(Index2 == 0){
if(Index == i){
if(Inventory[i].ItemId == 0){
if(Playerdata.HP != Playerdata.HPMAX){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.HP += 20;
A =!A;
}
}
if(Inventory[i].ItemId == 1){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.poisened = false;
A =!A;
}
if(Inventory[i].ItemId == 2){
t = false;
Inventory[i].capacity -= 10;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.amount += 10;
A =!A;
}
if(Inventory[i].ItemId == 3){
if(faceDoor){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.UseKey = false;
A =!A;
}
}
if(Inventory[i].ItemId == 4)
{
Color colorT = saveColor;
colorT.a = 0.1f;
USEtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 5)
{
Color colorT = saveColor;
colorT.a = 0.1f;
USEtext.color = colorT;
A =!A;
}
}
openOption = true;
}
}
//======Item Caoacity = 0 Erase ===================================================================
if(Inventory[i].capacity <= 0){
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
Destroy(testText.gameObject);
Inventory.Remove(Inventory[i]);
openOption = false;
itemOption.SetActive(false);
//icon.gameObject.SetActive(true);
//iconMini.gameObject.SetActive(false);
return;
}
}
//========================================================================================================================
}
//=====CHECK FOR ITEM IF EXIST AND ADD ITEM TO INVENTORY ================================================================================================
public void AddItem(int id) {
Item itemADD = data.fetchItem(id);
if(CheckForItemExist(itemADD)) {
for (int i = 0; i < Inventory.Count; i++) {
if(Inventory[i].ItemId == id) {
t = false;
Inventory[i].capacity ++;
testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Debug.Log (testText.text);
if(Inventory[i].Itemtype == Item.ItemType.ammo) {
Inventory[i].capacity += 10;
Inventory[i].capacity -= 1;
testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
}
break;
}
}
}else{
for (int i = 0; i < Inventory.Count; i++) {
if(Inventory[i].ItemId == -1){
t = true;
Inventory[i] = itemADD;
DesplayInventory();
}
}
}
}
//====================================================================================================
bool CheckForItemExist(Item item) {
for (int i = 0; i < Inventory.Count; i++)
if(Inventory[i].ItemId == item.ItemId)
return true;
return false;
}
//====================================================================================================
public void DesplayInventory() {
for (int i = 0; i < Inventory.Count; i++) {
var _text =Instantiate(Resources.Load("Text",typeof (Text)))as Text;
testText =_text;
_text.transform.position = panel.transform.position;
_text.transform.SetParent(panel);
_text.transform.localScale = new Vector3(1,1,1);
break;
}
}
}
//===========================================================================================================
and here is the Item script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[System.Serializable]
public class Item {
public int ItemId;
public string Itemname;
public ItemType Itemtype;
public int ItemPower;
public int capacity;
public enum ItemType
{
weapon,
spells,
consumable,
ammo,
}
public Item(int id,string name,int power,ItemType type,int cap)
{
capacity = cap;
ItemId = id;
Itemname = name;
ItemPower = power;
Itemtype = type ;
}
public Item()
{
this.ItemId = -1;
}
}
and here is the item Data Base script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ItemDatabase : MonoBehaviour {
public List<Item> items = new List<Item>();
void Start()
{
items.Add (new Item (0, "Potion", 0, Item.ItemType.consumable,1));
items.Add (new Item (1, "Antidot", 0, Item.ItemType.consumable, 1));
items.Add (new Item (2, "Arrows", 0, Item.ItemType.ammo,10));
items.Add (new Item (3, "KEY", 0, Item.ItemType.consumable,1));
items.Add (new Item (4, "sword", 15, Item.ItemType.weapon,1));
items.Add (new Item (5, "bow", 50, Item.ItemType.weapon,1));
}
public Item fetchItem(int id)
{
for (int i = 0 ; i < items.Count;i++)
if(items[i].ItemId == id)
return items[i];
return null;
}
}
It looks like you are missing the Serializeable attribute.
Add it to your Item class like so ->
[Serializable]
public class Item {
///Your code here
}
Related
I've been working on a project for the GMTK 2022 Game Jam recently, and I ran into a very strange problem. I have a dash that starts when you are moving and press space. It moves you in the direction of your velocity, then for a short time lets you move very quickly. It works perfectly fine in all cases, unless the direction you are moving is up and to the left, in which case, the if statement strangely won't trigger. I'm sure this is something idiotic, but I've been troubleshooting it for the last hour and it's been driving me insane.
// Update is called once per frame
void Update()
{
playerInputh = 0;
playerInputv = 0;
if (Input.GetKey("right"))
{
playerInputh = 1;
}
if (Input.GetKey("left"))
{
playerInputh = -1;
}
if (Input.GetKey("right") && Input.GetKey("left"))
{
playerInputh = 0;
}
if (Input.GetKey("up"))
{
playerInputv = 1;
}
if (Input.GetKey("down"))
{
playerInputv = -1;
}
if (Input.GetKey("up") && Input.GetKey("down"))
{
playerInputv = 0;
}
Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
//This is the dash that isn't working:
if ((Input.GetKeyDown(/*"right shift"*/"space")) && (playerInputh != 0 || playerInputv != 0))
{
Debug.Log("Dash");
//Vector2 transform2dposition = new Vector2(transform.position.x, transform.position.y);
m_Rigidbody.AddForce((m_Rigidbody.velocity) * 500f);
wJumpTimer = airControlAfterJump;
speed = maxSpeed*3.5f;
StartCoroutine(Roll());
}
}
void FixedUpdate()
{
//no moving while jumping!!!
if (wJumpTimer > 0)
{
wJumpTimer -= 1;
}
else
{
wJumpTimer = 0;
}
//move
if (playerInputh != 0 && playerInputv != 0) //make diagonals no super sayan
{
playerInputh *= moveLimiter;
playerInputv *= moveLimiter;
one_h = playerInputh;//futureproof
one_v = playerInputv;
}
if ((playerInputh != 0 || playerInputv != 0) && speed < maxSpeed) //are we hitting the move buttons??
{
speed += acceleration;//accelerate
one_h = playerInputh;//futureproof
one_v = playerInputv;
}
else
{
if (speed > 0f) //are we getting off the ride
{
speed -= deceleration; //decelerate
}
else
{
speed = 0f; //no funny buisness
}
}
m_Rigidbody.velocity = new Vector2(one_h * speed, one_v * speed); //actually move
}
void SetFace(int diceNumb)
{
rndr.sprite = sprites[diceNumb];
}
IEnumerator Roll()
{
Random diceNumb = new Random();
rndr.sprite = sprites[diceNumb.Next(0,5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
var newValue = diceNumb.Next(0, 5);
FaceValue = newValue + 1;
rndr.sprite = sprites[newValue];
}
How are your inputs setup? I am suspecting you have one key bound to multiple actions, like one key is set up as primary for an action and alternate for another action.
Personally I'd also stop using the assignment operators and increment instead. Instead of
playerInputh = 0;
if (Input.GetKey("right"))
{
playerInputh = 1;
}
if (Input.GetKey("left"))
{
playerInputh = -1;
}
if (Input.GetKey("right") && Input.GetKey("left"))
{
playerInputh = 0;
}
you can do
playerInputv = 0;
if (Input.GetKey("right"))
{
playerInputh += 1;
}
if (Input.GetKey("left"))
{
playerInputh += -1;
}
Net result is the same here - if you push both keys the result sums to zero, but the code is easier to read (IMO).
When you check things for key bindings also check alternates for space, because that's another one of the triggers you need to dash.
Here is my code:
void Update()
{
if (shipController.Mode == ShipController.ShipMode.Build)
{
var mouseInWorld = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
Debug.Log(mouseInWorld);
var mousePos = new Vector2(mouseInWorld.x, mouseInWorld.y);
var currentPos = new Vector2(transform.position.x, transform.position.y);
var posToTarget = mousePos - currentPos;
var oldPosToTarget = posToTarget;
var oldPos = currentPos;
var shotPastTargetOrExact = false;
var iter = 0;
while (!shotPastTargetOrExact)
{
iter++;
Debug.Log(iter);
oldPos = currentPos;
oldPosToTarget = posToTarget;
if (posToTarget == Vector2.zero) shotPastTargetOrExact = true;
if (Mathf.Abs(posToTarget.x) >= Mathf.Abs(posToTarget.y))
{
if (posToTarget.x > 0) currentPos = new Vector2(currentPos.x += blockdistance, currentPos.y);
else currentPos = new Vector2(currentPos.x -= blockdistance, currentPos.y);
}
else
{
if (posToTarget.y > 0) currentPos = new Vector2(currentPos.x, currentPos.y += blockdistance);
else currentPos = new Vector2(currentPos.x, currentPos.y -= blockdistance);
}
posToTarget = mousePos - currentPos;
if (posToTarget.sqrMagnitude > oldPosToTarget.sqrMagnitude)
{
shotPastTargetOrExact = true;
currentPos = oldPos;
}
}
if (currentSlot != null && currentSlot.CurrentItemDragAndDrop != null && currentSlot.CurrentItemDragAndDrop.Item != null)
{
var item = currentSlot.CurrentItemDragAndDrop.Item;
if (currentPlacementBlock == null)
{
currentPlacementBlock = Instantiate(item.BlockPrefab);
}
currentPlacementBlock.transform.localPosition = currentPos;
currentPlacementBlock.transform.rotation = shipController.transform.rotation;
}
else if (currentPlacementBlock != null)
{
Destroy(currentPlacementBlock);
currentPlacementBlock = null;
}
}
}
It crashes when I try to stop the game with the play button in the editor. It has also crashed when starting build mode (see shipController.Mode)
The script works as intended but crashes when stopping the game.
I loged the iterations to try and see if it was looping forever but it doesnt seem to be that as it always comes out with a small iter number in the console
I fixed it by checking if the mouse was in the window before going ahead and performing the rest of the update
bool IsMouseOverGameWindow { get { var mousePosition = Mouse.current.position.ReadValue(); return !(0 > mousePosition.x || 0 > mousePosition.y || Screen.width < mousePosition.x || Screen.height < mousePosition.y); } }
I have a problem with drag and drop on game. I want to block user if he is dragging the object from down to up in case they have sticks in same angles. if they dont so it is ok. But if they have even one stick in same direction so stick should go back to down to first position.
I am lost a bit. Can you help please :)
here is the code where I drag and drop also rotation...
Here on the pic generated stick group can fit only 1. and 3. places.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputController : MonoBehaviour
{
float clickTime;
RaycastHit2D rayhit;
float smallestDistance = 1.5f;
int smallestId = 1;
public Transform[] nodes;
public LayerMask selectableObjLayerMask;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickTime = Time.time;
rayhit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, selectableObjLayerMask);
}
else if (Input.GetMouseButtonUp(0))
{
if (rayhit)
{
if (Time.time - clickTime < .2f)
{
Node node = rayhit.transform.GetComponent<Node>();
if (node != null)
{
for (int i = 0; i < node.sticks.Count; i++)
{
Vector3 newAngles = new Vector3(0, 0, (node.sticks[i].transform.localEulerAngles.z - 45));
newAngles.z = newAngles.z < 0 ? newAngles.z + 180 : newAngles.z;
newAngles.z = newAngles.z >180 ? newAngles.z - 180 : newAngles.z;
node.sticks[i].transform.localEulerAngles = newAngles;
node.sticks[i].degree = (int)newAngles.z;
Debug.Log(i + " = " + node.sticks[i].degree);
}
}
}
else
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode.isMoved == false)
{
smallestId = 0;
smallestDistance = 999;
for (int i = 0; i < nodes.Length; i++)
{
float distance = Vector2.Distance(rayhit.transform.position, nodes[i].transform.position);
if (smallestDistance > distance)
{
smallestDistance = distance;
smallestId = i;
Debug.Log("Obje : " + currNode);
}
}
rayhit.transform.position = nodes[smallestId].transform.position;
if (rayhit.transform.parent != nodes[smallestId].transform)
{
if (nodes[smallestId].transform.childCount > 0 && nodes[smallestId].transform != rayhit.transform.parent)
{
if (currNode != null)
{
for (int i = 0; i < currNode.sticks.Count; i++)
{
nodes[smallestId].transform.GetChild(0).GetComponent<Node>().sticks.Add(currNode.sticks[i]);
currNode.sticks[i].transform.SetParent(nodes[smallestId].transform.GetChild(0));
}
Destroy(rayhit.transform.gameObject);
}
}
else
{
if (currNode != null)
{
currNode.isMoved = true;
}
rayhit.transform.SetParent(nodes[smallestId].transform);
}
}
}
}
}
rayhit = new RaycastHit2D();
}
else if (Input.GetMouseButton(0))
{
if(rayhit.transform != null)
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode != null)
if (currNode.isMoved == false)
{
if (Time.time - clickTime >= 0.2f)
{
Vector2 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rayhit.transform.position = newPos;
}
}
}
}
}
}
I try to creacte some buildings in 2d, but it should not be touched with the other buildings.I have a
private GameObject building;
From Update i called function
buildFence(Vector2 nextPos)
where i create new building
And from this function i called function which must return boolean type
public bool canbuild()
{
//Debug.Log(building);
if (building.GetComponent<Rigidbody2D>().IsTouchingLayers(LayerMask.GetMask("Buildings")))
{
building.GetComponent<SpriteRenderer>().color = Color.red;
//Debug.Log("canb=false");
return false;
}
else {
building.GetComponent<SpriteRenderer>().color = Color.green;
return true;
}
}
but this function always return true. If i called the same function from Update,
everything works well.
All code here
void Update()
{
if (mode)
{
if (TEST)
{
if (!UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButtonDown(0) && idBuilding != 0 && buildFlag)
{
buildFlag = false;
startpos = cam.ScreenToWorldPoint(Input.mousePosition);
if (idBuilding != 1)
{
building = (GameObject)Instantiate(buildings[idBuilding - 1], startpos, new Quaternion(0, 0, 0, 0));
building.GetComponent<Collider2D>().isTrigger = true;
canbuild();
}
else
{
}
}
if (Input.GetMouseButton(0) && idBuilding != 0)
{
if (idBuilding != 1)
{
Vector2 pos = cam.ScreenToWorldPoint(Input.mousePosition);
building.transform.position = pos;
canbuild();
}
else
{
buildFence(cam.ScreenToWorldPoint(Input.mousePosition));
if (!canbuild())
{
Debug.Log("succes");
}
}
}
if (Input.GetMouseButtonUp(0) && idBuilding != 0)
{
if (canbuild())
{
buildFlag = false;
Vector2 viewportPoint = Camera.main.WorldToViewportPoint(building.transform.position + new Vector3(2, 2, 0));
bAccept.anchorMin = viewportPoint;
bAccept.anchorMax = viewportPoint;
bAccept.gameObject.active = true;
}
else
{
Debug.Log("CantBuild");
Destroy(building);
buildFlag = true;
}
//building.GetComponent<Collider2D>().enabled = true;
}
}
}
else
{
}
}
}
void buildFence(Vector2 nextPos)
{
Vector2 delta = nextPos - startpos;
//Debug.Log("v2" + (nextPos - startpos));
//Debug.Log("v2.angle="+ Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
//Debug.Log("v2.angle=" +);
if (delta.magnitude >= 2.55 && canBuildNext)
{
if (delta.x < 0)
building = (GameObject)Instantiate(buildings[0], startpos, Quaternion.Euler(0, 0, Vector2.Angle(new Vector2(x, y), (nextPos - startpos))));
else
building = (GameObject)Instantiate(buildings[0], startpos, Quaternion.Euler(0, 0, -Vector2.Angle(new Vector2(x, y), (nextPos - startpos))));
building.GetComponent<Collider2D>().isTrigger = true;
canBuildNext = false;
}
if (!canBuildNext)
{
if (!canbuild(ref building))
{
Debug.Log("HERE");
if (delta.x < 0)
building.transform.rotation = Quaternion.Euler(0, 0, Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
else
building.transform.rotation = Quaternion.Euler(0, 0, -Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
}
else
{
startpos = nextPos;
//building.GetComponent<Collider2D>().isTrigger = false;
Zabor.Push(building);
canBuildNext = true;
}
}
}
public bool canbuild()
{
//Debug.Log(b);
//Debug.Log(building);
if (building.GetComponent<Rigidbody2D>().IsTouchingLayers(LayerMask.GetMask("Buildings")))
{
building.GetComponent<SpriteRenderer>().color = Color.red;
//Debug.Log("canb=false");
buildfail = false;
return false;
}
else {
building.GetComponent<SpriteRenderer>().color = Color.green;
buildfail = true;
return true;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm making a game (Breakout) and I have a question,
The question is how can I remove the barriers after they get hit by the ball?
Of course, the ball must be able to go through the track after that (like Breakout game in general)
the next question is that can I make the barriers in run time mode?
Thanks
private void timer1_Tick(object sender, EventArgs e)
{
ball.Top += step;
ball.Left += stepleft;
//board simulate collision
bool collisonX = ball.Location.X + ball.Width > board.Location.X && ball.Location.X < board.Location.X + board.Width;
bool collisonY = ball.Top + ball.Height == board.Location.Y || ball.Top + ball.Height - 1 == board.Location.Y;
//board2(button1) simulate collision
bool collisonX2 = ball.Location.X + ball.Width > board2.Location.X && ball.Location.X < board2.Location.X + board2.Width;
bool collisonY2 = ball.Top + ball.Height == board2.Location.Y || ball.Top + ball.Height - 1 == board2.Location.Y;
//Collision the ball with under buttons
bool collsionButtonY = ball.Top - ball.Height == board2.Location.Y || ball.Top - ball.Height == board2.Location.Y - 1;
//collision leftwall
bool leftWall = ball.Left == 0 || ball.Left == -1 || ball.Left == 1;
//collision rightwall
bool topWall = ball.Top == 0 || ball.Top == -1 || ball.Top == 1;
bool bottomWall = collisonX && collisonY;
bool toppWall = collisonX2 && collisonY2;
//collision
bool barrier = collisonX2 && collsionButtonY;
bool collisionLeft = ((ball.Location.Y + ball.Height >= board2.Location.Y) && (ball.Location.Y <= board2.Location.Y + board2.Height) && (ball.Location.X + ball.Width >= board2.Location.X) && (ball.Location.X <= board2.Location.X + board2.Height));
//rightwall
bool rightWall = ball.Left + ball.Width == this.ClientSize.Width || ball.Left + ball.Width == this.ClientSize.Width - 1;
// sidewall = collision rightwall or leftwall
bool sideWall = leftWall || rightWall;
//Check the ball hit the ground
bool check = ball.Top + ball.Height < this.ClientSize.Height;
//if topWall true,This means that the ball is hit to the topwall
if (topWall)
{
flagBottom = false;
flagTop = true;
if (stepleft > 0)
{
step = 2;
}
else if (stepleft < 0)
{
step = 2;
}
}
//if bottomWall true,This means that the ball is hit to the board
else if (bottomWall)
{
flagBottom = true;
flagTop = false;
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
//if barrier true and flagbottom true,This means that the ball is hit to the board2(button1)
else if (barrier && flagBottom)
{
collisionLeft = false;
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
//if toppWall true and flagTop true,This means that the ball is hit to The top button is hit
else if (toppWall && flagTop)
{
collisionLeft = false;
if (stepleft > 0)
{
step = step * -1;
}
else if (stepleft < 0)
{
step = step * -1;
}
}
else if (flagTop && collisionLeft)
{
barrier = false;
if (stepleft > 0)
{
stepleft = -2;
step = 2;
}
else if (stepleft < 0)
{
stepleft = 2;
step = 2;
}
}
else if (flagBottom && collisionLeft)
{
barrier = false;
if (stepleft > 0)
{
stepleft = -2;
step = -2;
}
else if (stepleft < 0)
{
stepleft = 2;
step = -2;
}
}
else if (sideWall)
{
//if leftwall true,This means that the ball is hit to the left side wall
if (leftWall)
{
if (flagTop)
{
stepleft = 2;
}
else if (flagBottom)
{
stepleft = 2;
}
}
//if rightWall true,This means that the ball is hit to the left side wall
else if (rightWall)
{
if (flagTop)
{
stepleft = -2;
}
else if (flagBottom)
{
stepleft = -2;
}
}
}
//check if ckeck==ture,this mean the ball is hit the ground
else if (!check)
{
timer1.Enabled = false;
}
}
private void board_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
MouseDownLocation = e.Location;
}
}
private void board_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
board.Left = e.X + board.Left - MouseDownLocation.X;
}
You need to learn use lists and proper use of classes.
For example :
public class GameObject{
public GameObject(int x, int y, int width, int height){
this.X = x;
this.Y = y;
this.Width = width;
this.Height = height;
}
int X;
int Y;
int Width;
int Height;
public bool DetectCollision(bool Ball){
//code to detect collision
}
}
Then in your main class, you can do thing like that.
List<GameObject> gameObjects = new List<GameObject>();
gameObjects.add(new GameObject(10,10,50,50));
gameObjects.add(new GameObject(20,10,20,50));
gameObjects.add(new GameObject(30,10,50,70));
gameObjects.add(new GameObject(40,10,90,50));
And to detect the collisions :
foreach (GameObject gameObject in gameObjects){
if (gameObject.DetectCollision(ball)){
//do something
}
}