I am suffering from a strange bug in my project. It runs in unity perfectly but when I build it for IOS, it does one thing in particular differently. When a user picks up 8 items, I have an input box display these items and what order they selected them in. This works perfectly in unity but doesn't in IOS. Anyone have any suggestions as to why this might be the case. Below are the two appropriate scripts.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class PickUpItem : MonoBehaviour, IInteractable
{
//Go back to older version of clavem, find out what broke.
public string DisplaySprite;
public string DisplayImage;
public static string ItemChoosenOrder;
public static int counter;
public static GameObject InventorySlots;
public static GameObject[] PlayerItems = new GameObject[8];
public void Interact(DisplayImage currentDisplay)
{
ItemPickUp();
}
void Start()
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
}
void Update()
{
}
public void ItemPickUp()
{
InventorySlots = GameObject.Find("Slots");
counter = 0;
foreach (Transform slot in InventorySlots.transform)
{
if (slot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
slot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
if (counter <= 7)
{
counter++;
if (counter >= 7)
{
{
Debug.Log("You have choosen all your items.");
foreach (Transform finalslot in InventorySlots.transform)
{
if (finalslot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
finalslot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
}
//https://hub.packtpub.com/arrays-lists-dictionaries-unity-3d-game-development/
if (PlayerItems[7].GetComponent<Image>().sprite.name != "empty_item")
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
ItemChoosenOrder = "1: " + PlayerItems[0].GetComponent<Image>().sprite.name + " 2: " + PlayerItems[1].GetComponent<Image>().sprite.name
+ " 3: " + PlayerItems[2].GetComponent<Image>().sprite.name + " 4: " + PlayerItems[3].GetComponent<Image>().sprite.name
+ " 5: " + PlayerItems[4].GetComponent<Image>().sprite.name + " 6: " + PlayerItems[5].GetComponent<Image>().sprite.name
+ " 7: " + PlayerItems[6].GetComponent<Image>().sprite.name + " 8: " + PlayerItems[7].GetComponent<Image>().sprite.name;
Debug.Log(ItemChoosenOrder);
Debug.Log(counter);
}
else
{
Debug.Log("Error choosing items");
}
}
}
}
}
}
}
saveitemhash
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveItemHash : MonoBehaviour
{
public InputField choosenitems;
public Text playerDisplay;
public Text InfoText;
public Button SaveButton;
private void Awake()
{
if (DBManager.email == null)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
playerDisplay.text = "User: " + DBManager.email;
}
public void CallAddItems()
{
StartCoroutine(AddChoosenItems());
}
IEnumerator AddChoosenItems()
{
//Using a unity web request to send email and choosen items string to my php scripts which echo a number depending on whether the user is successful or not.
WWWForm form = new WWWForm();
form.AddField("email", DBManager.email);
form.AddField("items", choosenitems.text);
WWW www = new WWW("https://clavem.000webhostapp.com/userregister.php", form);
yield return www;
if (www.text[0] == '0')
{
Debug.Log("User added successfully.");
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
else
{
Debug.Log("User adding failed. Error #" + www.text);
InfoText.text = www.text;
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
}
public void Update()
{
playerDisplay.text = "User: " + DBManager.email;
if (PickUpItem.counter > 7)
{
//Do this for add field in last scene where the passwords are.
GameObject.Find("SaveButton").transform.localScale = new Vector3(1, 1, 1);
choosenitems.text = PickUpItem.ItemChoosenOrder;
GameObject.Find("InputField").transform.localScale = new Vector3(1, 1, 1);
//choosenitems.text = PickUpItem.ItemChoosenOrder;
//Debug.Log(PickUpItem.ItemChoosenOrder);
}
if (PickUpItem.counter < 7)
{
GameObject.Find("SaveButton").transform.localScale = new Vector3(0, 0, 0);
GameObject.Find("InputField").transform.localScale = new Vector3(0, 0, 0);
}
}
public void RestartScene()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(3); ;
PickUpItem.counter = 0;
PickUpItem.ItemChoosenOrder = " ";
}
}
Working answer using a List collection and directly linking the order by adding each item to the array corresponding to each inventory slot in the appropriate order.
PickUpItem Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Linq;
public class PickUpItem : MonoBehaviour, IInteractable
{
public string DisplaySprite;
public string DisplayImage;
public static List<string> itemOrder = new List<string>();
public static string ItemChoosenOrder;
public static int counter;
public static GameObject InventorySlots;
public static GameObject[] PlayerItems = new GameObject[8];
public void Interact(DisplayImage currentDisplay)
{
ItemPickUp();
}
void Start()
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
}
void Update()
{
}
public void ItemPickUp()
{
InventorySlots = GameObject.Find("Slots");
counter = 0;
int j;
foreach (Transform slot in InventorySlots.transform)
{
if (slot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
slot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
if (counter <= 7)
{
//itemOrder.Add(PlayerItems[counter].GetComponent<Image>().sprite.name);
counter++;
if (counter >= 7)
{
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
Debug.Log("You have choosen all your items.");
foreach (Transform finalslot in InventorySlots.transform)
{
if (finalslot.transform.GetChild(0).GetComponent<Image>().sprite.name == "empty_item")
{
finalslot.transform.GetChild(0).GetComponent<Image>().sprite =
Resources.Load<Sprite>("Inventory Items/" + DisplaySprite);
Destroy(gameObject);
break;
}
}
itemOrder.Add(GameObject.Find("item0").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item1").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item2").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item3").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item4").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item5").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item6").GetComponent<Image>().sprite.name);
itemOrder.Add(GameObject.Find("item7").GetComponent<Image>().sprite.name);
//https://hub.packtpub.com/arrays-lists-dictionaries-unity-3d-game-development/
if (PlayerItems[7].GetComponent<Image>().sprite.name != "empty_item")
{
PlayerItems = GameObject.FindGameObjectsWithTag("ChoosenItem");
for (j = 0; j < 8; j++)
{
Debug.LogFormat("Item[{0}] = {1}", j, itemOrder[j]);
}
ItemChoosenOrder = "1: " + itemOrder[0] + " 2: " + itemOrder[1]
+ " 3: " + itemOrder[2] + " 4: " + itemOrder[3]
+ " 5: " + itemOrder[4] + " 6: " + itemOrder[5]
+ " 7: " + itemOrder[6] + " 8: " + itemOrder[7];
Debug.Log(ItemChoosenOrder);
}
else
{
Debug.Log("Error choosing items");
}
}
}
}
}
}
}
Related
I'm currently working on a virtual pet game, and I need help to solve this issue, as fast as possible.
I'm trying to get the timeSpan of between now and the last time I've played, and the script doesn't continue after the part of the timeSpan (Mentioned below the script, including the main question).
The Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird : MonoBehaviour {
[SerializeField]
private int _hunger;
[SerializeField]
private int _happiness;
[SerializeField]
private string _name;
private bool _servertime;
private int _clickCount;
DateTime timeSpan4;
void Start()
{
print("Then: " + PlayerPrefs.GetString("then"));
print("getStringTime(): " + getStringTime());
print("TimeOfDay: " + DateTime.Now.TimeOfDay);
print("DateTime now: " + DateTime.Now);
//PlayerPrefs.SetString("then", "09 / 12 / 2019 20:50:0");
updateStatus();
//if (!PlayerPrefs.HasKey("name"))
// PlayerPrefs.SetString("name", "Bird");
_name = PlayerPrefs.GetString("name");
}
void Update()
{
GetComponent<Animator>().SetBool("Fly", gameObject.transform.position.y > -2.3);
if (Input.GetMouseButtonUp(0))
{
//Debug.Log("Clicked");
Vector2 v = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(v), Vector2.zero);
if (hit)
{
//Debug.Log(hit.transform.gameObject.name);
if(hit.transform.gameObject.tag == "Birb")
{
_clickCount++;
if(_clickCount >= 3)
{
_clickCount = 0;
updateHappiness(5);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 1000));
}
}
}
}
}
public void updateStatus()
{
print("Updating Status...");
if (!PlayerPrefs.HasKey("_hunger"))
{
_hunger = 100;
PlayerPrefs.SetInt("_hunger", _hunger);
}
else
{
_hunger = PlayerPrefs.GetInt("_hunger");
}
if (!PlayerPrefs.HasKey("_happiness"))
{
_happiness = 100;
PlayerPrefs.SetInt("_happiness", _happiness);
}
else
{
_happiness = PlayerPrefs.GetInt("_happiness");
}
if (!PlayerPrefs.HasKey("then"))
PlayerPrefs.SetString("then", getStringTime());
TimeSpan ts = getTimeSpan();
_hunger -= (int)(ts.TotalHours * 2);
if (_hunger < 0)
{
_hunger = 0;
PlayerPrefs.SetInt("_hunger", _hunger);
}
if (_hunger > 100)
{
_hunger = 100;
PlayerPrefs.SetInt("_hunger", _hunger);
print("hunger is bigger than 100!");
}
_happiness -= (int)((100 - _hunger) * (ts.TotalHours / 5));
if (_happiness < 0)
{
_happiness = 0;
PlayerPrefs.SetInt("_happiness", _happiness);
}
if (_happiness > 100)
{
_happiness = 0;
PlayerPrefs.SetInt("_happiness", _happiness);
}
//Debug.Log(getTimeSpan().ToString());
//Debug.Log(getTimeSpan().TotalHours);
if (_servertime)
updateServer();
else
InvokeRepeating("saveBird", 0f, 2f);
}
void updateServer()
{
}
void updateDevice()
{
PlayerPrefs.SetString("then", getStringTime());
}
TimeSpan getTimeSpan()
{
if (_servertime)
return new TimeSpan();
else
return DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("then"));
}
string getStringTime()
{
DateTime now = DateTime.Now;
return now.Day + "-" + now.Month + "-" + now.Year + " " + now.Hour + ":" + now.Minute + ":" + now.Second;
}
public int hunger
{
get { return _hunger; }
set { _hunger = value; }
}
public int happiness
{
get { return _happiness; }
set { _happiness = value; }
}
public string BName
{
get { return _name; }
set { _name = value; }
}
public void updateHappiness(int i)
{
happiness += i;
if (happiness > 100)
happiness = 100;
}
public void saveBird()
{
if (!_servertime)
updateDevice();
PlayerPrefs.SetInt("_hunger", _hunger);
PlayerPrefs.SetInt("_happiness", _happiness);
}
}
The problem is in line 134 (return DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("then"));), it prints FormatException: String was not recognized as a valid DateTime., and because of that the script doesn't continue after that part. How can I convert the string "then" to a DateTime so it won't error?
The exact format for loading a date from a string depends on a lot of factors. One of the most important being the locale.
That being said you're a lot safer if you use DateTimes string formatting methods instead of saving it by hand.
You can change your getStringTime() to rely on ToString and save that:
string getStringTime() {
return DateTime.Now.ToString();
}
I'm making a very simple Pokemon battle game with C#. The main idea is that every 5 turns the first Pokemon (Squirtle) powers up his damage with a function.
But when I compile it, the damage of Squirtle is the same. Any of idea what's happening?
Here's the code:
using System;
namespace FirstProgram
{
class MainClass
{
static void Main(string[]args)
{
int turn = 1;
int potion1 = 0;
//Creando y declarando Pikachu
Pokemon Pikachu = new Pokemon();
Pikachu.health = 190;
Pikachu.damage = 40;
//Creando y declarando Squirtle
Pokemon Squirtle = new Pokemon();
Squirtle.health = 190;
Squirtle.damage = 40;
while (Pikachu.health > 0 && Squirtle.health > 0)
{
if(turn == 1)
{
Squirtle.health = Squirtle.health - Pikachu.damage;
turn = 0;
potion1++;
Console.WriteLine("Pikachu atacks!");
Console.WriteLine("Squirtle has only " + Squirtle.health + " PV!");
if(potion1 == 5)
{
potion1 = 0;
Squirtle.MoreDamage(Squirtle.damage);
Console.WriteLine("Squirtle damage now it's " + Squirtle.damage);
}
}
else
{
Pikachu.health = Pikachu.health - Squirtle.damage;
turn = 1;
Console.WriteLine("Squirtle atacks!");
Console.WriteLine("Pikachu has only " + Pikachu.health + " PV!");
}
}
if(Pikachu.health > 0)
{
Console.WriteLine("Pikachu wins!");
}
else if(Squirtle.health > 0)
{
Console.WriteLine("Squirtle wins!");
}
}
}
}
Pokemon.cs
class Pokemon
{
//Declarando la vida y el ataque
public int health;
public int damage;
//Creando metodo para aumentar el ataque
public void MoreDamage(powerup)
{
powerup= powerup+ 5;
}
}
And here is the output:
I tried to do other things, like changing the code of the function, but all of the tries have the same result: the damage doesn't power up.
The MoreDamage() method is only modifying the powerup parameter. You need to edit the Pokemon's damage property instead.
Change this:
public void MoreDamage(powerup)
{
powerup= powerup+ 5;
}
to this:
public void MoreDamage(int powerup)
{
damage += powerup;
}
Then, change your call to MoreDamage() to pass the value you want to increase the Pokemon's damage by:
Squirtle.MoreDamage(5);
This question already has answers here:
StreamWriter.Write doesn't write to file; no exception thrown
(8 answers)
Closed 4 years ago.
This C# assignment is about creating groups for salesmen at diffrent levels depending how much they sold for, and then write this info to a textfile using a streamwriter.
I have done all parts except the streamwriter part. What i do so far is to create the file, but there is no ouput.
When i run this the content in the console is correct but the textfile becomes modified but blank.
The streamwriter is in the bottom part.
´
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inlämningsuppgift2
{
// Emplooyeklassen where names, personal info, district och sold items sparas och hämtas
class Emplooye
{
String namn;
int personnummer;
string distrikt;
int såldaartiklar;
int säljnivå;
public Emplooye(string namn, int personnummer, string distrikt, int såldaartiklar)
{
this.namn = namn;
this.personnummer = personnummer;
this.distrikt = distrikt;
this.såldaartiklar = såldaartiklar;
}
public string Name
{
get { return namn; }
set { namn = value; }
}
public int PersonNummer
{
get { return personnummer; }
set { personnummer = value; }
}
public string Distrikt
{
get { return distrikt; }
set { distrikt = value; }
}
public int AmountSold
{
get { return såldaartiklar; }
set { såldaartiklar = value; }
}
public int SäljNivå
{
get { return säljnivå; }
set { säljnivå = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inlämningsuppgift2;
using System.IO;
namespace ConsoleApp3
{
class Säljlista
{
static void Main(string[] args)
{
List<Emplooye> ObjSeller = new List<Emplooye>();
List<Emplooye> group1 = new List<Emplooye>();
List<Emplooye> group2 = new List<Emplooye>();
List<Emplooye> group3 = new List<Emplooye>();
ObjSeller.Add(new Emplooye("Oscar Norberg", 961111, "Täby", 140));
ObjSeller.Add(new Emplooye("jonas okembia", 970912, "Uppsala", 70));
ObjSeller.Add(new Emplooye("Mille vega", 981212, "Danderyd", 40));
ObjSeller.Add(new Emplooye("Isak friisjespesen", 991132, "Skåne", 80));
ObjSeller.Add(new Emplooye("Maja olofsson", 974132, "Täby", 123));
ObjSeller.Add(new Emplooye("Annmarie norberg", 944432, "Täby", 230));
ObjSeller.Add(new Emplooye("Ulla persson", 9312332, "Uppland", 124));
ObjSeller.Add(new Emplooye("Christer Nilsen", 9988332, "Vallentuna", 444));
Console.WriteLine("Namn Personnummer Distrikt Antal");
//Here the employees gets sorted in groups depending how much they sold for.
foreach (Emplooye e in ObjSeller)
{
if (e.AmountSold > 0 && e.AmountSold <= 90)
{
group1.Add(e);
}
else if (e.AmountSold > 90 && e.AmountSold <= 200)
{
group2.Add(e);
}
else
{
group3.Add(e);
}
}
group1.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group1.Count; i++)
{
string name = group1.ElementAt(i).Name;
int pnr = group1.ElementAt(i).PersonNummer;
String district = group1.ElementAt(i).Distrikt;
int amountsold = group1.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 1" + ": " + group1.Count);
Console.WriteLine("");
group2.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group2.Count; i++)
{
string name = group2.ElementAt(i).Name;
int pnr = group2.ElementAt(i).PersonNummer;
String district = group2.ElementAt(i).Distrikt;
int amountsold = group2.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 2 2" + ": " + group2.Count);
Console.WriteLine("");
group3.Sort(delegate (Emplooye t1, Emplooye t2)
{ return (t1.AmountSold.CompareTo(t2.AmountSold)); }
);
for (int i = 0; i < group3.Count; i++)
{
string name = group3.ElementAt(i).Name;
int pnr = group3.ElementAt(i).PersonNummer;
String district = group3.ElementAt(i).Distrikt;
int amountsold = group3.ElementAt(i).AmountSold;
Console.WriteLine(name + ": " + pnr + " - " + district + " - " + amountsold);
}
Console.WriteLine("salesmen at level 3" + ": " + group3.Count);
Console.WriteLine("");
StreamWriter SW = new StreamWriter("important.txt");
foreach(Emplooye i in group1)
{
SW.WriteLine(group1.ToString());
foreach(Emplooye i in group2)
{
SW.WriteLine(group2.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(group3.ToString());
}
}
}
You aren't closing the stream writer so it is buffering the output in memory but not writing to the file. Try a 'using' statement:
using(StreamWriter SW = new StreamWriter("important.txt"))
{
foreach(Emplooye i in group1)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group2)
{
SW.WriteLine(i.ToString());
}
foreach(Emplooye i in group3)
{
SW.WriteLine(i.ToString());
}
}
I got this error i cant really fix it i dont know what does it want me to do .
here is the code if you need more of the codes tell me if they will help you solve it .
using System;
using UnityEngine;
using Random = UnityEngine.Random;
public class LobbyMenu : MonoBehaviour
{
//private string[]FirstName = new string[7]{"Clever", "Cunning", "Wise", "Awesome", "Amazing", "Dark", "Heroic"};
//private string[]LastName = new string[7]{"Rogue", "Wizard", "Mage", "Summoner", "Warrior", "Assassin", "Ranger"};
private string roomName = "myRoom";
private bool MessageRoomNameTaken = false;
private float MessageRoomTakenTimeToDisplay = 0;
private Vector2 scrollPos = Vector2.zero;
private bool connectFailed = false;
public static readonly string SceneNameMenu = "LobbyScene";
public static readonly string SceneNameGame = "GameScene";
public void Awake()
{
// this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
PhotonNetwork.automaticallySyncScene = true;
// the following line checks if this client was just created (and not yet online). if so, we connect
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
{
// Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project)
PhotonNetwork.ConnectUsingSettings("1.0");
}
// generate a name for this player, if none is assigned yet
if (String.IsNullOrEmpty(PhotonNetwork.playerName))
{
//PhotonNetwork.playerName = "Guest" + Random.Range(1, 9999);
//PhotonNetwork.playerName = FirstName[Random.Range(0, 6)] + " " + LastName[Random.Range(0, 6)];
PhotonNetwork.playerName = MainMenu.username;
}
// if you wanted more debug out, turn this on:
// PhotonNetwork.logLevel = NetworkLogLevel.Full;
}
public void OnGUI()
{
if (!PhotonNetwork.connected)
{
if (PhotonNetwork.connecting)
{
GUILayout.Label("Connecting to: " + PhotonNetwork.ServerAddress);
}
else
{
GUILayout.Label("Not connected. Check console output. Detailed connection state: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.ServerAddress);
}
if (this.connectFailed)
{
GUILayout.Label("Connection failed. Check setup and use Setup Wizard to fix configuration.");
GUILayout.Label(String.Format("Server: {0}", new object[] {PhotonNetwork.ServerAddress}));
GUILayout.Label("AppId: " + PhotonNetwork.PhotonServerSettings.AppID);
if (GUILayout.Button("Try Again", GUILayout.Width(100)))
{
this.connectFailed = false;
PhotonNetwork.ConnectUsingSettings("1.0");
}
}
return;
}
GUI.skin.box.fontStyle = FontStyle.Bold;
GUI.Box(new Rect((Screen.width - 400) / 2, (Screen.height - 350) / 2, 400, 300), "Join or Create a Room");
GUILayout.BeginArea(new Rect((Screen.width - 400) / 2, (Screen.height - 350) / 2, 400, 300));
GUILayout.Space(25);
// Player name
GUILayout.BeginHorizontal();
GUILayout.Label("Player name:", GUILayout.Width(100));
GUILayout.Label(PhotonNetwork.playerName);
//PhotonNetwork.playerName = GUILayout.TextField(PhotonNetwork.playerName);
GUILayout.Space(105);
if (GUI.changed)
{
// Save name
PlayerPrefs.SetString("playerName", PhotonNetwork.playerName);
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
// Join room by title
GUILayout.BeginHorizontal();
GUILayout.Label("Roomname:", GUILayout.Width(100));
this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Create Room", GUILayout.Width(100)))
{
foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
{
if (roomInfo.name == this.roomName) {MessageRoomNameTaken = true; break;}
}
if (MessageRoomNameTaken==false) PhotonNetwork.CreateRoom(this.roomName, new RoomOptions() { maxPlayers = 2 }, null);
Debug.Log("OnJoinedRoom");
}
GUILayout.EndHorizontal();
// Create a room (fails if exist!)
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
//this.roomName = GUILayout.TextField(this.roomName);
if (GUILayout.Button("Join Room", GUILayout.Width(100)))
{
PhotonNetwork.JoinRoom(this.roomName);
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
// Join random room
GUILayout.BeginHorizontal();
GUILayout.Label(PhotonNetwork.countOfPlayers + " users are online in " + PhotonNetwork.countOfRooms + " rooms.");
GUILayout.FlexibleSpace();
if (GUILayout.Button("Join Random", GUILayout.Width(100)))
{
PhotonNetwork.JoinRandomRoom();
}
GUILayout.EndHorizontal();
GUILayout.Space(15);
if (PhotonNetwork.GetRoomList().Length == 0)
{
GUILayout.Label("Currently no games are available.");
GUILayout.Label("Rooms will be listed here, when they become available.");
}
else
{
int roomcount = PhotonNetwork.GetRoomList().Length;
if (roomcount==1 )GUILayout.Label("1 room is currently available:");
else GUILayout.Label(PhotonNetwork.GetRoomList().Length + " rooms are currently available:");
// Room listing: simply call GetRoomList: no need to fetch/poll whatever!
this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
{
GUILayout.BeginHorizontal();
GUILayout.Label(roomInfo.name + " " + roomInfo.playerCount + "/" + roomInfo.maxPlayers);
if (GUILayout.Button("Join"))
{
PhotonNetwork.JoinRoom(roomInfo.name);
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
GUILayout.EndArea();
if (MessageRoomNameTaken == true) {
MessageRoomTakenTimeToDisplay = 5; // we will display the warning for this number of seconds
MessageRoomNameTaken = false;
}
if (MessageRoomTakenTimeToDisplay >0 ) { GUI.contentColor = Color.red;
GUI.Label(new Rect(400,50,300,60), "The room with this name already exists");
MessageRoomTakenTimeToDisplay = MessageRoomTakenTimeToDisplay - Time.deltaTime;
}
}
// We have two options here: we either joined(by title, list or random) or created a room.
public void OnJoinedRoom()
{
Debug.Log("OnJoinedRoom");
}
public void OnCreatedRoom()
{
Debug.Log("OnCreatedRoom");
PhotonNetwork.LoadLevel(SceneNameGame);
}
public void OnDisconnectedFromPhoton()
{
Debug.Log("Disconnected from Photon.");
}
public void OnFailedToConnectToPhoton(object parameters)
{
this.connectFailed = true;
Debug.Log("OnFailedToConnectToPhoton. StatusCode: " + parameters + " ServerAddress: " + PhotonNetwork.networkingPeer.ServerAddress);
}
}
i used photon network so yea . so please just rewrite or fix it or atleast tell me what to do i have no clue .
// the following line checks if this client was just created (and not yet online). if so, we connect
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
{
// Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project)
PhotonNetwork.ConnectUsingSettings("1.0");
}
If you check the docs for PhotonNetwork you'll see that the PhotonNetwork.connectionStateDetailed static property returns a ClientState enum value (so not a PeerState).
Source: https://doc-api.photonengine.com/en/pun/current/class_photon_network.html
And here is the enum documentation: Enum Documentation
So, change:
if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated)
to
if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated)
Pls help me correct this problem.
Assets/Menu.cs(97,73): warning CS0618: UnityEditor.EditorUtility.GetAssetPath(UnityEngine.Object)' is obsolete:Use AssetDatabase.GetAssetPath'
Error building Player because scripts had compiler errors
Assets/Menu.cs(2,7): error CS0246: The type or namespace name `UnityEditor' could not be found. Are you missing a using directive or an assembly reference?
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
using System.Linq;
struct ObjMaterial
{
public string name;
public string textureName;
}
public class Menu : MonoBehaviour {
public int window;
void Start () {
window = 1;
}
private static int vertexOffset = 0;
private static int normalOffset = 0;
private static int uvOffset = 0;
//User should probably be able to change this. It is currently left as an excercise for
//the reader.
private static string targetFolder = "ExportedObj";
private static string MeshToString(Component mf, Dictionary<string, ObjMaterial> materialList)
{
Mesh m;
Material[] mats;
if(mf is MeshFilter)
{
m = (mf as MeshFilter).mesh;
mats = mf.GetComponent<Renderer>().sharedMaterials;
}
else if(mf is SkinnedMeshRenderer)
{
m = (mf as SkinnedMeshRenderer).sharedMesh;
mats = (mf as SkinnedMeshRenderer).sharedMaterials;
}
else
{
return "";
}
StringBuilder sb = new StringBuilder();
sb.Append("g ").Append(mf.name).Append("\n");
foreach(Vector3 lv in m.vertices)
{
Vector3 wv = mf.transform.TransformPoint(lv);
//This is sort of ugly - inverting x-component since we're in
//a different coordinate system than "everyone" is "used to".
sb.Append(string.Format("v {0} {1} {2}\n",-wv.x,wv.y,wv.z));
}
sb.Append("\n");
foreach(Vector3 lv in m.normals)
{
Vector3 wv = mf.transform.TransformDirection(lv);
sb.Append(string.Format("vn {0} {1} {2}\n",-wv.x,wv.y,wv.z));
}
sb.Append("\n");
foreach(Vector3 v in m.uv)
{
sb.Append(string.Format("vt {0} {1}\n",v.x,v.y));
}
for (int material=0; material < m.subMeshCount; material ++) {
sb.Append("\n");
sb.Append("usemtl ").Append(mats[material].name).Append("\n");
sb.Append("usemap ").Append(mats[material].name).Append("\n");
//See if this material is already in the materiallist.
try
{
ObjMaterial objMaterial = new ObjMaterial();
objMaterial.name = mats[material].name;
objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);
//else
//objMaterial.textureName = null;
materialList.Add(objMaterial.name, objMaterial);
}
catch (ArgumentException)
{
//Already in the dictionary
}
int[] triangles = m.GetTriangles(material);
for (int i=0;i<triangles.Length;i+=3)
{
//Because we inverted the x-component, we also needed to alter the triangle winding.
sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
triangles[i]+1 + vertexOffset, triangles[i+1]+1 + normalOffset, triangles[i+2]+1 + uvOffset));
}
}
vertexOffset += m.vertices.Length;
normalOffset += m.normals.Length;
uvOffset += m.uv.Length;
return sb.ToString();
}
private static void Clear()
{
vertexOffset = 0;
normalOffset = 0;
uvOffset = 0;
}
private static Dictionary<string, ObjMaterial> PrepareFileWrite()
{
Clear();
return new Dictionary<string, ObjMaterial>();
}
private static void MaterialsToFile(Dictionary<string, ObjMaterial> materialList, string folder, string filename)
{
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl"))
{
foreach( KeyValuePair<string, ObjMaterial> kvp in materialList )
{
sw.Write("\n");
sw.Write("newmtl {0}\n", kvp.Key);
sw.Write("Ka 0.6 0.6 0.6\n");
sw.Write("Kd 0.6 0.6 0.6\n");
sw.Write("Ks 0.9 0.9 0.9\n");
sw.Write("d 1.0\n");
sw.Write("Ns 0.0\n");
sw.Write("illum 2\n");
if (kvp.Value.textureName != null)
{
string destinationFile = kvp.Value.textureName;
int stripIndex = destinationFile.LastIndexOf('/');//FIXME: Should be Path.PathSeparator;
if (stripIndex >= 0)
destinationFile = destinationFile.Substring(stripIndex + 1).Trim();
string relativeFile = destinationFile;
destinationFile = folder + "/" + destinationFile;
Debug.Log("Copying texture from " + kvp.Value.textureName + " to " + destinationFile);
try
{
//Copy the source file
File.Copy(kvp.Value.textureName, destinationFile);
}
catch
{
}
sw.Write("map_Kd {0}", relativeFile);
}
sw.Write("\n\n\n");
}
}
}
private static void MeshToFile(Component mf, string folder, string filename)
{
Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
sw.Write(MeshToString(mf, materialList));
}
MaterialsToFile(materialList, folder, filename);
}
private static void MeshesToFile(Component[] mf, string folder, string filename)
{
Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
for (int i = 0; i < mf.Length; i++)
{
sw.Write(MeshToString(mf[i], materialList));
}
}
MaterialsToFile(materialList, folder, filename);
}
private static bool CreateTargetFolder()
{
try
{
System.IO.Directory.CreateDirectory(targetFolder);
}
catch
{
//EditorUtility.DisplayDialog("Error!", "Failed to create target folder!", "");
return false;
}
return true;
}
void OnGUI () {
GUI.BeginGroup (new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100, 200, 200));
if(window == 1)
{
if(GUI.Button (new Rect (10,30,180,30), "Экспортировать"))
{
if (!CreateTargetFolder())
return;
//GameObject[] gos = GameObject.FindGameObjectsWithTag("Boat");
//Selection.objects = gos;
GameObject[] selection = GameObject.FindGameObjectsWithTag("Boat");
//Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
if (selection.Length == 0)
{
//EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
return;
}
int exportedObjects = 0;
ArrayList mfList = new ArrayList();
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter)).Concat(selection[i].GetComponentsInChildren(typeof(SkinnedMeshRenderer))).ToArray();
for (int m = 0; m < meshfilter.Length; m++)
{
exportedObjects++;
mfList.Add(meshfilter[m]);
}
}
if (exportedObjects > 0)
{
Component[] mf = new Component[mfList.Count];
for (int i = 0; i < mfList.Count; i++) {
mf [i] = (Component)mfList [i];
}
string filename = /*EditorApplication.currentScene +*/ "_" + exportedObjects;
int stripIndex = filename.LastIndexOf ('/');//FIXME: Should be Path.PathSeparator
if (stripIndex >= 0)
filename = filename.Substring (stripIndex + 1).Trim ();
MeshesToFile (mf, targetFolder, filename);
}
}
if(GUI.Button (new Rect (10,150,180,30), "Выход"))
{
window = 5;
}
}
if(window == 5)
{
GUI.Label(new Rect(50, 10, 180, 30), "Вы уже выходите?");
if(GUI.Button (new Rect (10,40,180,30), "Да"))
{
Application.Quit();
}
if(GUI.Button (new Rect (10,80,180,30), "Нет"))
{
window = 1;
}
}
GUI.EndGroup ();
}
}
Before using any Unity API, it is very important to check the API namespace. If the namespace is from UnityEditor then it is only meant to work in the Editor only. This is used to make an Editor plugin. You can't use it in a build and it will throw an error when building for any platform.
According the docs, AssetDatabase and EditorUtility class are from the UnityEditor namespace.
You have to re-design your game to work without the GetAssetPath function. You can definitely make a game without that function. I can't tell what you are doing but you should look into the Resources class. This will help you load your GameObjects during run-time.
To solve your current problem,
Replace
using UnityEditor;
with
#if UNITY_EDITOR
using UnityEditor;
#endif
Then replace
objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);
with
objMaterial.textureName = "";
#if UNITY_EDITOR
objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);
#endif
You can also put your Menu script in a folder in the Assets/Editor directory but please understand that this does not solve the problem that your code won't work in a build. It will only allow your project to build without those errors in your question. The classes from the UnityEditor namespace are only used for Editor plugin.
This happens because classes that are using UnityEditor need to be put under a folder called Editor: Assets/Editor
If you do that, the problem will be gone
If you are using Assembly definitions (dlls) this can also happen. No dll that includes editor stuff will be included in the build. Best to make a separate dll for editor stuff.