I have a code that saves data in the data file are saved without any problem.But I also tried to save an array but the array was not saved and I get an error.I keep the data (and also the array) in BinaryFormatter.The error indicates the line bf.Serialize (file, data) before closing the file in the save function.
the code
public class SaveLoadScript : MonoBehaviour
{
public int allMoneyOfplayer, allXpOfPlayer, laval, maxXp, howMuchUpMaxXp;
public float highTime;
public List<GunScript> gun = new List<GunScript>();
public void Start()
{
Save();
}
public void Update()
{
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/saveG.file");
PlayerData data = new PlayerData();
data.money = allMoneyOfplayer;
data.xp = allXpOfPlayer;
if (highTime > data.time)
data.time = highTime;
data.laval = laval;
data.maxXp = maxXp;
data.howMuchUpMaxXp = howMuchUpMaxXp;
for (int i = 0; i < gun.Count; i++)
data.gun.Add(gun[i]);
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/saveG.file"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/saveG.file", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
allMoneyOfplayer = data.money;
allXpOfPlayer = data.xp;
highTime = data.time;
laval = data.laval;
maxXp = data.maxXp;
howMuchUpMaxXp = data.howMuchUpMaxXp;
file.Close();
}
}
}
[System.Serializable]
class PlayerData
{
public int money;
public int xp;
public float time;
public int laval;
public int maxXp;
public int howMuchUpMaxXp;
public List<GunScript> gun = new List<GunScript>();
}
the error
SerializationException: Type 'GunScript' in Assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers (System.RuntimeType type) (at :0)
System.Runtime.Serialization.FormatterServices+<>c__DisplayClass9_0.b__0 (System.Runtime.Serialization.MemberHolder _) (at :0)
System.Collections.Concurrent.ConcurrentDictionary2[TKey,TValue].GetOrAdd (TKey key, System.Func2[T,TResult] valueFactory) (at :0)
System.Runtime.Serialization.FormatterServices.GetSerializableMembers (System.Type type, System.Runtime.Serialization.StreamingContext context) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo () (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo memberObjectInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo typeNameInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize (System.Object graph, System.Runtime.Remoting.Messaging.Header[] inHeaders, System.Runtime.Serialization.Formatters.Binary.__BinaryWriter serWriter, System.Boolean fCheck) (at :0)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph, System.Runtime.Remoting.Messaging.Header[] headers, System.Boolean fCheck) (at :0)
[System.Serializable] //<-- add this attribute
public class GunScript
I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading
Related
\I want to make a socket application that will run on Linux and provide multiple messaging and file transfer. Can you share sample code? Can you help me i am a second year computer engineering student?
I found a similar code in my research, but I cannot connect to my linux server from different computers.I learned this code from github #HondaPL.
This is client codes
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using MessengerLogic;
using System.IO;
namespace Messenger
{
public class Connection
{
public static int BufferSize = 1024;
public static string nick;
public static IPAddress ip = IPAddress.Parse("-.-.-.-");
public static int port = 1234;
public static TcpClient client = new TcpClient();
public static List<string> users = new List<string>();
public static bool isEnd = false;
public static string[] fromServer = new string[30];
public void Connect(string nickname)
{
nick = nickname;
client.Connect(ip, port);
nickname += "$Welcome$";
byte[] buffer = Encoding.ASCII.GetBytes(nickname);
NetworkStream ns = client.GetStream();
Console.WriteLine(nickname);
ns.Write(buffer, 0, buffer.Length);
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
StringParser parser = new StringParser();
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
fromServer = new string[30];
users.Clear();
string message = Encoding.ASCII.GetString(receivedBytes, 0, byte_count);
fromServer = parser.Parser(message);
if (fromServer[0] == "List")
{
for (int i = 1; i < fromServer.Length; i++)
{
users.Add(fromServer[i]);
}
isEnd = true;
}
else
{
Console.WriteLine(message);
Console.WriteLine(fromServer[0]);
Console.WriteLine(fromServer[1]);
FrmOnlineUsers.frm.AssignValues(fromServer[0], fromServer[1]);
FrmOnlineUsers.frm.MessageFromClient();
}
}
}
public List<string> Refresh()
{
NetworkStream ns = client.GetStream();
string temp = nick;
temp += "$List$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
while (!isEnd)
{
}
isEnd = false;
return users;
}
public void SendMessage(string who, string msg)
{
NetworkStream ns = client.GetStream();
string temp = $"{who}$Message${msg}$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
}
public void FileSend(string filepath, string nick, string fileName)
{
NetworkStream ns = client.GetStream();
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
byte[] bytesToSend = new byte[fs.Length];
int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
int totalBytes = 0;
//Tutaj trzeba dodać, aby pobierał nazwę pliku
string temp = $"{nick}$File${fileName}${fs.Length}";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
Thread.Sleep(1000);
for (int i = 0; i <= fs.Length / BufferSize; i++)
{
if (fs.Length - (i * BufferSize) > BufferSize)
{
ns.Write(bytesToSend, i * BufferSize,
BufferSize);
totalBytes += BufferSize;
}
else
{
ns.Write(bytesToSend, i * BufferSize,
(int)fs.Length - (i * BufferSize));
totalBytes += (int)fs.Length - (i * BufferSize);
}
}
fs.Close();
}
}
}
Hello programmers all around the world. I have made myself an inventory system for my game. Only problem is that when I click on item and then drag it to and empty slot it doesn't move and I kinda don't see the error which I am having and I have tried to debug it but without success any help? Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Inventory : MonoBehaviour {
private RectTransform inventoryRect;
private float inventoryWidth;
private float inventoryHeight;
public int slots;
public int rows;
public float slotPaddingLeft;
public float slotPaddingTop;
public float slotSize;
public GameObject slotPrefab;
private static Slot from;
private static Slot to;
private List<GameObject> allslots;
public GameObject iconPrefab;
private static GameObject hoverObject;
private static int emptySlots;
public Canvas canvas;
private float hoverYOffset;
private bool isPressed;
public EventSystem eventSystem;
public static int EmptySlots{
get{ return emptySlots;}
set{ emptySlots = value;}
}
// Use this for initialization
void Start () {
CreateLayout ();
canvas.enabled = false;
isPressed = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.I)) {
if (Input.GetKeyDown (KeyCode.I)) {
canvas.enabled = false;
}
canvas.enabled = true;
}
if (Input.GetMouseButtonUp (0)) {
if (!eventSystem.IsPointerOverGameObject (-1) && from != null) {
from.GetComponent<Image> ().color = Color.white;
from.ClearSlot ();
Destroy (GameObject.Find ("Hover"));
to = null;
from = null;
hoverObject = null;
}
}
if (hoverObject != null) {
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle (canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
position.Set (position.x, position.y - hoverYOffset);
hoverObject.transform.position = canvas.transform.TransformPoint (position);
}
}
private void CreateLayout(){
allslots = new List<GameObject> ();
hoverYOffset = slotSize * 0.01f;
emptySlots = slots;
inventoryWidth = (slots / rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
inventoryHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
inventoryRect = GetComponent<RectTransform> ();
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, inventoryWidth);
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, inventoryHeight);
int colums = slots / rows;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < colums; x++) {
GameObject newSlot = (GameObject)Instantiate (slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform> ();
newSlot.name = "Slot";
newSlot.transform.SetParent (this.transform.parent);
slotRect.localPosition = inventoryRect.localPosition + new Vector3 (slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, slotSize);
allslots.Add (newSlot);
}
}
}
public bool AddItem(Item item){
if (item.maxSize == 1) {
PlaceEmpty (item);
return true;
}
else {
foreach (GameObject slot in allslots) {
Slot temporary = slot.GetComponent<Slot> ();
if (!temporary.IsEmpty) {
if (temporary.CurrentItem.type == item.type && temporary.IsAvailable) {
temporary.AddItem (item);
return true;
}
}
}
if (emptySlots > 0) {
PlaceEmpty (item);
}
}
return false;
}
private bool PlaceEmpty(Item item){
if (emptySlots > 0) {
foreach (GameObject slot in allslots) {
Slot temporary = slot.GetComponent<Slot> ();
if (temporary.IsEmpty) {
temporary.AddItem (item);
emptySlots--;
return true;
}
}
}
return false;
}
public void MoveItem(GameObject clicked){
if (from == null) {
if (!clicked.GetComponent<Slot> ().IsEmpty) {
from = clicked.GetComponent<Slot> ();
from.GetComponent<Image> ().color = Color.gray;
hoverObject = (GameObject)Instantiate (iconPrefab);
hoverObject.GetComponent<Image> ().sprite = clicked.GetComponent<Image> ().sprite;
hoverObject.name = "Hover";
RectTransform hoverTransform = hoverObject.GetComponent<RectTransform> ();
RectTransform clickedTransform = clicked.GetComponent<RectTransform> ();
hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, clickedTransform.sizeDelta.x);
hoverTransform.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, clickedTransform.sizeDelta.y);
hoverObject.transform.SetParent (GameObject.Find ("Canvas").transform, true);
hoverObject.transform.localScale = from.gameObject.transform.localScale;
}
}
else if (to = null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
if (to != null && from != null) {
Stack<Item> tmpTo = new Stack<Item> (to.Items);
to.AddItems (from.Items);
if (tmpTo.Count == 0) {
from.ClearSlot ();
}
else {
from.AddItems (tmpTo);
}
from.GetComponent<Image> ().color = Color.white;
to = null;
from = null;
hoverObject = null;
}
}
}
The method which is causing the problem is the MoveItem() sadly it is not a nullreference or nullpointer and I simply am out of ideas been strugling with it for a couple of days... Any advice on how to fix this would be helpfull and much welcomed indeed. Thanks in advance!
I haven't taken a long look at your code but right away I saw this issue:
else if (to = null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
This is causing the end location to be set to null. To fix this, change to double equals like so:
else if (to == null) {
to = clicked.GetComponent<Slot> ();
Destroy (GameObject.Find ("Hover"));
}
If this does not solve your problem, let me know and I'll look at your code harder.
My unity player keeps on freezing after a while, I know what script is causing it (if it is indeed a script that is causing it). since there's only one script I've edited when it started freezing. But I can't figure out WHY it is freezing!
Here is the script that is causing it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
//public GameObject allPlayersPrefab;
public GameObject allPlayers;
public Transform playerRed;
public Transform playerGreen;
//public Transform playerPurple;
//public Transform playerYellow;
//Tail redTail;
//Tail greenTail;
//Tail purpleTail;
//Tail yellowTail;
public float secondsBetweenGaps = 2f;
public float secondsToGap = .25f;
public float snakeSpeed = 3f;
public float turnSpeed = 200f;
public int biggerPickupDuration = 3;
public int smallerPickupDuration = 3;
public int speedPickupDuration = 2;
public int invinciblePickupDuration = 3;
public int maxPickups = 3;
public int spawnPickupThreshold = 5;
private GameObject[] currPickups;
public GameObject[] pickupTypes;
public Transform pickupsParent;
public int players = 2;
[HideInInspector]
public int alive;
public bool enableKeys = false;
public GameObject prefabTail;
public GameObject settingsMenu;
public GameObject startingPanel;
public Text scoreText;
public Text radiusText;
public Text speedText;
public Text winText;
private bool hasEnded = false;
[HideInInspector]
public bool playerWon = false;
public bool running;
public Snake[] snakes;
ButtonManager buttonManager;
Pickup[] pickups;
void Start() {
//InstantiateNewPlayers();
playerRed = allPlayers.transform.FindChild("Red");
playerGreen = allPlayers.transform.FindChild("Green");
snakes = allPlayers.GetComponentsInChildren<Snake>(true);
alive = players;
//redTail = playerRed.GetComponentInChildren<Tail>();
//greenTail = playerGreen.GetComponentInChildren<Tail>();
//purpleTail = playerPurple.GetComponentInChildren<Tail>();
//yellowTail = playerYellow.GetComponentInChildren<Tail>();
buttonManager = FindObjectOfType<ButtonManager>();
pickups = FindObjectsOfType<Pickup>();
playerRed.gameObject.SetActive(false);
playerGreen.gameObject.SetActive(false);
//playerPurple.gameObject.SetActive(false);
//playerYellow.gameObject.SetActive(false);
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
void Update() {
if(Input.GetKey(KeyCode.Escape)) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
buttonManager.anima.Play("BackToSettings");
playerWon = true;
ResetGame();
buttonManager.restartButt.gameObject.SetActive(false);
buttonManager.StopAllCoroutines();
buttonManager.countDownText.enabled = false;
winText.enabled = false;
foreach(Snake snake in snakes) {
snake.scoreText.enabled = false;
}
}
if(alive == 1 && !hasEnded) {
Transform lastPlayer;
foreach(Snake child in snakes) {
if(!child.dead) {
lastPlayer = child.transform.parent;
if(child.score >= int.Parse(scoreText.text)) {
Win(lastPlayer.name);
AllPlayersDead();
} else
AllPlayersDead();
break;
}
}
}
if(alive == 0) {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
foreach(Snake child in snakes) {
if(child.score >= int.Parse(scoreText.text)) {
AllPlayersDead();
Win(child.transform.parent.name);
}
}
}
public void AllPlayersDead() {
if(hasEnded)
return;
buttonManager.restartButt.gameObject.SetActive(true);
hasEnded = true;
running = false;
}
void Win(string winningPlayer) {
foreach(Snake snake in snakes) {
snake.score = 0;
snake.scoreText.text = "0";
}
Debug.Log("Win got called");
winText.gameObject.SetActive(true);
winText.enabled = true;
winText.text = winningPlayer + " wins!";
playerWon = true;
running = false;
}
public void PlayerDied() {
foreach(Snake child in snakes) {
if(!child.dead) {
child.score += 1;
}
}
}
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
}
}
}
public void ResetGame() {
Debug.Log("Resetting everything...");
for(int i = 0; i < players; i++) {
Transform currPlayer = allPlayers.transform.GetChild(i);
currPlayer.GetComponentInChildren<Tail>().points.Clear();
currPlayer.GetComponentInChildren<Snake>().dead = false;
currPlayer.GetComponentInChildren<Snake>().invincible = false;
currPlayer.GetComponentInChildren<Snake>().posInformer.position = new Vector3(-20, 0, 0);
if(playerWon) {
currPlayer.GetComponentInChildren<Snake>().score = 0;
playerWon = false;
}
//currPlayer.GetComponentInChildren<LineRenderer>().positionCount = 0;
currPlayer.GetComponentInChildren<LineRenderer>().numPositions = 0;
List<Vector2> list = new List<Vector2>();
list.Add(new Vector2(0, 5));
list.Add(new Vector2(0, 6));
StopAllCoroutines();
for(int i2 = 0; i2 < pickups.Length; i2++) {
pickups[i2].StopAllCoroutines();
}
foreach(Transform pickup in pickupsParent) {
Destroy(pickup.gameObject);
}
currPlayer.GetComponentInChildren<EdgeCollider2D>().points = list.ToArray();
foreach(Transform child in currPlayer) {
if(child.CompareTag("PrefabTail")) {
Destroy(child.gameObject);
}
}
currPlayer.gameObject.SetActive(false);
currPlayer.GetComponentInChildren<Tail>().enabled = true;
Destroy(GameObject.FindWithTag("PrefabTail"));
turnSpeed = int.Parse(radiusText.text) * 10;
snakeSpeed = float.Parse(speedText.text);
alive = players;
hasEnded = false;
running = false;
}
Debug.Log("Resetting done.");
}
}
I do have a small suspection that the freezing has something to do with the SpawnPickups method and/or the part where it destroys the pickups in the ResetGame method.
Thanks!
Your method SpawnPickups is doing this.
When you call this coroutine, and enable is true and running is false, you never reach a "yield" instruction, so your while(enabled) is indeed a while(true)
Coroutines are not threads, they run on the main thread and if you block a coroutine like this one, you are blocking the game.
public IEnumerator SpawnPickups() {
while(enabled) {
Debug.Log("SpawnPickups running...");
if(running) {
if(pickupsParent.childCount < maxPickups) {
int type = Random.Range(0, pickupTypes.Length);
float X = Random.Range(-7f, 7f);
float Y = Random.Range(-3f, 3f);
Vector3 spawnPos = new Vector3(X, Y, 0);
/*GameObject newPickup = */Instantiate(pickupTypes[type], spawnPos, Quaternion.Euler(0, 0, 0), pickupsParent);
Debug.Log("SpawnPickups instantiated new pickup...");
yield return new WaitForSeconds(spawnPickupThreshold);
}
//Here you need some yield in case running is true but you reached maxPickups (this one is not necessary if you put the next one)
}
//Here you need some yield in case running is false
//yield return null; //this should be enough to prevent your game from freezing
}
}
I'm trying to pass a public int score value from one script to another script but it is giving me the error an object reference is required to access non-static member , here it is what I have done
public class firearrow : MonoBehaviour {
public GameObject Arrow;
public GameObject apple;
public int score = 0;
// Use this for initialization
void Start () {
this.gameObject.GetComponent<Rigidbody2D> ().AddForce (transform.right*1500.0f);
}
// Update is called once per frame
void Update () {
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 0);
if (Input.GetMouseButtonUp (0)) {
GameObject bullet_new;
bullet_new = Instantiate (Arrow,new Vector2 (-0.23f, -3.78f), Quaternion.identity) as GameObject;
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector2.zero);
if (hit.collider!= null ) {
LeanTween.move(bullet_new, hit.collider.transform.localPosition, 1);
if(hit.collider.tag == "fruit")
{
score++;
Destroy(hit.collider.gameObject,1);
Destroy(bullet_new,1);
}
}
}
}
}
the class I want to access the score
public class tick : MonoBehaviour {
public Text wintext;
// Use this for initialization
void Start () {
wintext.text = "";
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonUp (0)) {
if(firearrow.score == 3)
{
wintext.text="You Win";
}
}
}
}
Any suggestions?
Change line
public int score = 0;
to
public static int score = 0;
Note that you must only have one single instance of class firearrow, otherwise you might run into concurrency issues.
When I run the following code on Windows 7 and 8.1 I get different results. On Windows 7 if I re-run the code on the newly created file it throws exceptions while the Windows 8.1 code works fine.
Any Clues?????
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string a = #"C:\temp\Materials\20130911134612877_3.pdf";
string b = #"C:\temp\Materials\20130911134612877_4.pdf";
Program p = new Program();
p.Open(a);
p.SaveSource(b);
}
public List<Bitmap> Bitmaps { get; private set; }
private string sourceFileName { get; set; }
private string destPath { get; set; }
public List<int> Source { get; set; }
public List<int> Destination { get; set; }
public void Open(string fileName)
{
this.sourceFileName = fileName;
this.destPath = Path.Combine(Path.GetDirectoryName(fileName), "Processed");
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(this.destPath);
}
string original = Path.Combine(Path.GetDirectoryName(fileName), "Orginal", Path.GetFileName(fileName));
if (!File.Exists(original))
{
string originalPath = Path.GetDirectoryName(original);
if (!Directory.Exists(originalPath))
{
Directory.CreateDirectory(originalPath);
}
File.Copy(fileName, original);
}
if (this.Bitmaps != null)
{
for (int _i = 0; _i < this.Bitmaps.Count; _i++)
{
this.Bitmaps[_i].Dispose();
}
}
PDFDocument doc = GetDocument(fileName);
this.Bitmaps = new List<Bitmap>();
this.Source = new List<int>();
this.Destination = new List<int>();
for (int i = 0; i < doc.Count; i++)
{
this.Source.Add(i);
this.Bitmaps.Add(doc.GetImage(i));
}
doc.Close();
}
public void SaveSource(string file)
{
if (this.Source.Count != 0)
{
PDFDocument pdf = new PDFDocument();
pdf.FileName = file;
foreach (int i in this.Source)
{
pdf.Add(this.Bitmaps[i]);
}
pdf.Close();
}
else
{
if (File.Exists(this.sourceFileName))
{
File.Delete(this.sourceFileName);
}
}
}
private PDFDocument GetDocument(string file)
{
PDFDocument doc = null;
doc = new PDFDocument();
doc.Open(file);
return doc;
}
public static void MergePdfFiles(IEnumerable<string> files, string output)
{
iTextSharp.text.Document doc;
iTextSharp.text.pdf.PdfCopy pdfCpy;
doc = new iTextSharp.text.Document();
pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(output, System.IO.FileMode.Create));
doc.Open();
foreach (string file in files)
{
// initialize a reader
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
int pageCount = reader.NumberOfPages;
// set page size for the documents
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
for (int pageNum = 1; pageNum <= pageCount; pageNum++)
{
iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, pageNum);
pdfCpy.AddPage(page);
}
reader.Close();
}
doc.Close();
}
}
public class MyImageRenderListener : IRenderListener
{
public void RenderText(TextRenderInfo renderInfo) { }
public void BeginTextBlock() { }
public void EndTextBlock() { }
public Bitmap Image = null;
public void RenderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
using (MemoryStream ms = new MemoryStream(image.GetImageAsBytes()))
{
Bitmap i = (System.Drawing.Bitmap)Bitmap.FromStream(ms);
Image = (System.Drawing.Bitmap)i.Clone();
i.Dispose();
// int dpi = i.Height / 11;
int yDPI = Image.Height / 11;
int xDPI = (Image.Width * 2) / 17;
xDPI = Math.Abs(xDPI - 300) < 10 ? 300 : xDPI;
yDPI = Math.Abs(yDPI - 300) < 10 ? 300 : yDPI;
xDPI = Math.Abs(xDPI - 600) < 10 ? 600 : xDPI;
yDPI = Math.Abs(yDPI - 600) < 10 ? 600 : yDPI;
if (xDPI == yDPI)
{
Image.SetResolution(xDPI, yDPI);
}
else
{
}
}
}
catch (IOException)
{
/*
* pass-through; image type not supported by iText[Sharp]; e.g. jbig2
*/
}
}
}
public class PDFDocument
{
public string FileName { get; set; }
~PDFDocument()
{
this.Close();
}
public static void AddImage(Stream inputPdfStream, Stream outputPdfStream, Stream inputImageStream)
{
PdfReader reader = new PdfReader(inputPdfStream);
iTextSharp.text.Rectangle size = reader.GetPageSize(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(size.Width - 98, size.Height - 98);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
int page = 1;
// for (int page = 1; page <= reader.NumberOfPages; page++)
{
PdfContentByte pdfContentByte = stamper.GetOverContent(page);
pdfContentByte.AddImage(image);
}
stamper.Close();
}
public void Open(string fileName)
{
this.reader = new PdfReader(fileName);
this.parser = new PdfReaderContentParser(reader);
this.listener = new MyImageRenderListener();
}
public int Count { get { return reader.NumberOfPages; } }
public Bitmap GetImage(int index)
{
parser.ProcessContent(index + 1, listener);
return listener.Image;
}
public Bitmap GetImage2(int index)
{
PdfDictionary page = reader.GetPageN(index + 1);
return GetImagesFromPdfDict(page);
}
private PdfReaderContentParser parser = null;
private MyImageRenderListener listener = null;
private PdfReader reader = null;
private Bitmap GetImagesFromPdfDict(PdfDictionary dict)
{
PdfDictionary res = (PdfDictionary)(PdfReader.GetPdfObject(dict.Get(PdfName.RESOURCES)));
PdfDictionary xobj = (PdfDictionary)(PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)));
Bitmap bm = null;
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)(PdfReader.GetPdfObject(obj));
PdfName subtype = (PdfName)(PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)));
if (PdfName.IMAGE.Equals(subtype))
{
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = this.reader.GetPdfObject(xrefIdx);
PRStream str = (PRStream)(pdfObj);
iTextSharp.text.pdf.parser.PdfImageObject pdfImage = new iTextSharp.text.pdf.parser.PdfImageObject(str);
bm = (System.Drawing.Bitmap)pdfImage.GetDrawingImage();
bm.SetResolution(300.0f, 300.0f);
break;
}
else if (PdfName.FORM.Equals(subtype) || PdfName.GROUP.Equals(subtype))
{
GetImagesFromPdfDict(tg);
}
}
}
}
return bm;
}
public void Split(string fileName)
{
throw new NotImplementedException();
}
public void Save(System.Drawing.Bitmap bm, string filename)
{
Save(bm, filename, RotateFlipType.RotateNoneFlipNone);
}
const float PAGE_LEFT_MARGIN = 0;
const float PAGE_RIGHT_MARGIN = 0;
const float PAGE_TOP_MARGIN = 0;
const float PAGE_BOTTOM_MARGIN = 0;
public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate)
{
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN))
{
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
pdfDocument.Open();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
pdfDocument.Close();
writer.Close();
}
}
}
public void Add(System.Drawing.Bitmap bm)
{
this.Add(bm, RotateFlipType.RotateNoneFlipNone);
}
FileStream stream;
iTextSharp.text.Document pdfDocument;
iTextSharp.text.pdf.PdfWriter writer;
public void Add(System.Drawing.Bitmap bm, System.Drawing.RotateFlipType rotate)
{
if (this.stream == null)
{
this.stream = new FileStream(this.FileName, FileMode.Create);
this.pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN);
this.writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
this.pdfDocument.Open();
}
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
ms.Seek(0, SeekOrigin.Begin);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
}
}
public void Close()
{
if (this.pdfDocument != null)
{
this.pdfDocument.Close();
this.pdfDocument.Dispose();
this.writer.Close();
this.writer.Dispose();
this.stream.Close();
this.stream.Dispose();
this.pdfDocument = null;
this.writer = null;
this.pdfDocument = null;
}
if (this.reader != null)
{
this.reader.Close();
}
}
public void Tag(string oldFile, Stream fs, string text)
{
float x;
float y;
// open the reader
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
float height = 60;
float width = 150;
x = size.Width - 40 - width;
y = size.Height - height;
Document document = new Document(size);
// open the writer
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
cb.Rectangle(x, y, width, height);
cb.SetColorFill(BaseColor.WHITE);
cb.Fill();
// close the streams and voilá the file should be changed :)
// write the text in the pdf content
cb.BeginText();
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 20);
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x + 5, y + 10, 0);
cb.EndText();
writer.Flush();
document.Close();
reader.Close();
// fs.Seek(0, SeekOrigin.Begin);
}
}
}