This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've received two files: Sumator.cs and Kalkulator.cs # Visual Studio 2012
I think you don't need to see those two, but I did put them here anyways, go down page and check my problem.
Sumator.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Sumator
{
bool Status = false;
double Suma = 0;
public Kalkulator Kalk = new Kalkulator();
public Sumator()
{
}
public void ZmienStatus()
{
Status = !Status;
}
public string PokazStatus()
{
if (Status == true)
return " Sumator włączony";
else
return " Sumator wyłaczony";
}
public void PokazWynikS()
{
if (Status == true)
Suma += Kalk.Wynik;
Console.WriteLine("Wynik działania : " + Kalk.L1.ToString() + " " + Kalk.Dzialanie.ToString() + " " + Kalk.L2.ToString() + " = " + Kalk.Wynik.ToString() + PokazStatus() + " Suma= " + Suma.ToString());
}
public void Zeruj()
{
Suma = 0;
}
}
}
Kalkulator.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Kalkulator
{
public double L1;
public double L2;
public double Wynik;
public String Dzialanie = "";
public Kalkulator()
{
}
void Oblicz()
{
switch (Dzialanie)
{
case "+":
Wynik = L1 + L2;
break;
case "-":
Wynik = L1 - L2;
break;
case "*":
Wynik = L1 * L2;
break;
case "/":
Wynik = L1 / L2;
break;
}
}
public void PodajDzialanie(double licz1, double licz2, string dz)
{
L1 = licz1;
L2 = licz2;
Dzialanie = dz;
Oblicz();
}
public void PokazWynik()
{
Console.WriteLine("Wynik działania : " + L1.ToString() + " " + Dzialanie.ToString() + " " + L2.ToString() + " = " + Wynik.ToString());
}
}
}
and I've written my main code for those two.
Program.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sumator2
{
class Program
{
static void Main(string[] args)
{
Sumator s1 = new Sumator();
s1.ZmienStatus();
bool userNum = true;
while (userNum)
{
double userDouble;
string userString = Console.ReadLine();
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
s1.Kalk.PodajDzialanie(userDouble, 2, "+");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
Console.ReadKey();
}
}
}
Problem is that I wanted to use s1.Kalk.PodajDzialanie() function with those arguments:
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
and I got error like:
The name 'userDouble' does not exists in the current context
I mean wt*? This function does work normally if I do like:
s1.Kalk.PodajDzialanie(2, 2, "*");
You're declaring userDouble inside your while loop. Once you leave that loop, it's out of scope. Move it to before the loop and you should be fine. So instead you have:
bool userNum = true;
double userDouble;
while (userNum)
{
string userString = Console.ReadLine();
// Jesli sa liczby to convertujemy
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
You're declaring userDouble in a scope that the function does not have access to.
Change your code to this:
static void Main(string[] args)
{
Sumator s1 = new Sumator();
double userDouble; //moved declaration out of while loop
s1.ZmienStatus();
// Sprawdzanie czy w stringu sa liczby
bool userNum = true;
while (userNum)
{
string userString = Console.ReadLine();
// Jesli sa liczby to convertujemy
if (userNum = double.TryParse(userString, out userDouble))
{
userDouble = Convert.ToDouble(userString);
userNum = false;
}
else
{
Console.WriteLine("Nie podano liczby!");
userNum = true;
}
}
s1.Kalk.PodajDzialanie(userDouble, 2, "*");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
s1.Kalk.PodajDzialanie(userDouble, 2, "+");
s1.PokazWynikS();
s1.Kalk.PokazWynik();
Console.ReadKey();
}
Your variable double userDouble; is declared within the while loop, you need to move it outside. Or mvoe your s1.Kalk.PodajDzialanie(userDouble, 2, "*"); inside the while loop before it ends.
Your variable userDouble is declared inside a block and the call you are trying to do is outside of that block; hence, the variable is out of scope, and thus doesn't exist in the context of the call.
{
declaration;
work;
}
call; // doesn't work
But this does work:
declaration;
{
work;
}
call; // OK
Related
this is how my GUI looks like
I was working on a project for uni
what it does is reading a text-file
put it in listbox1
then the second button should take the students who succeed to listbox2
but whenever I press the button I get an error
I tried rly hard to search everywhere, but couldn't find the problem
it's just not writing it in listbox2 for no reason
anyone know what should I do?
what do I do to make it work???
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace second_Project
{
public partial class FSS : Form
{
private void FSS_Load(object sender, EventArgs e)
{
}
public FSS()
{
InitializeComponent();
}
public class StdScore
{
public int id;
public string name;
public double xam, Score, Pract;
public string content;
public string[] xx;
}
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
StdScore StdScore = new StdScore();
ofd.Filter = "TXT|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
while (!sr.EndOfStream)
{
StdScore.content = sr.ReadLine();
string[] info = StdScore.content.Split(' ');
StdScore.xx = new string[info.Length];
listBox1.Items.Add(StdScore.content);
}
sr.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
StdScore StdScore = new StdScore();
StdScore.xam = 0;
StdScore.Pract = 0;
StdScore.Score = 0;
StdScore.xam += int.Parse(StdScore.xx[2]);
StdScore.Pract += int.Parse(StdScore.xx[3]);
StdScore.Score = StdScore.xam * 0.7 + StdScore.Pract * 0.3;
if (StdScore.xam >= 40 && StdScore.Pract >= 40 && StdScore.Score >= 60)
{
StdScore.xam = (StdScore.xam * 70) / 100;
StdScore.Pract = (StdScore.Pract * 30) / 100;
StdScore.Score = StdScore.xam + StdScore.Pract;
listBox2.Items.Add(StdScore.xx[0] + " " + StdScore.xx[1] + " " + StdScore.xx[2] + " " + StdScore.xx[3] + " " + StdScore.Score + " " + "Succes");
}
}
}
}
When reading the file, you have listBox1.Items.Add(StdScore.content);. This simply adds a string to the ListBox. You should create instances of StdScore INSIDE the while loop and add those instances directly to the ListBox. It's a very bad practice to name your variable the exact same as the class itself. I would expect to see something more like StdScore curScore = new StdScore();. Now you can use curScore and it's clear this is an instance of the class and not the class itself, and you're not trying to access a static member. For class StdScore, you can override the ToString() method to control what is displayed in the ListBox.
So here is StdScore with the ToString() override:
public class StdScore
{
public int id;
public string name;
public double xam, Score, Pract;
public string content;
public string[] xx;
public override string ToString()
{
return content;
}
}
Next, reading the file:
while (!sr.EndOfStream)
{
StdScore curScore = new StdScore();
curScore.content = sr.ReadLine();
curScore.xx = curScore.content.Split(' ');
listBox1.Items.Add(curScore);
}
On to button2 where you want to move students who succeed over to listBox2. Here you need to ITERATE over all the stored StdScore instances that are within listBox1:
private void button2_Click(object sender, EventArgs e)
{
foreach(StdScore curScore in listBox1.Items)
{
curScore.xam = int.Parse(curScore.xx[2]);
curScore.Pract = int.Parse(curScore.xx[3]);
curScore.Score = curScore.xam * 0.7 + curScore.Pract * 0.3;
if (curScore.xam >= 40 && curScore.Pract >= 40 && curScore.Score >= 60)
{
curScore.xam = (curScore.xam * 70) / 100;
curScore.Pract = (curScore.Pract * 30) / 100;
curScore.Score = curScore.xam + curScore.Pract;
string success = curScore.xx[0] + " " + curScore.xx[1] + " " +
curScore.xx[2] + " " + curScore.xx[3] + " " + curScore.Score + " Success";
listBox2.Items.Add(success);
}
}
}
Note that from an Object Oriented Programming perspective, none of this code is correct. The code can be much improved. I simply took your existing code and changed it to "make it work"...at least I think it will; if not, it should give you some good ideas on where to make changes.
Hoping someone can help. I'm still learning a lot each day as beginner. But have a few issues with the below.
The use of goto is a no-no from the research I have seen but I can't figure out an alternative loop to add while maybe? Or do?
When I enter text that I know will not return a result e.g. dsfgfhg and press enter I receive "Resource Not found " three times in the results. I assume this is because out of the list there are three entries and none match. How do I get one result instead of three when a resource is not found?
If I press enter twice in the console window without entering any text it returns everything in the list. Again I can't see a way to stop this. I guess I need to change the code to be explicit in some way?
Thanks again for your help.
using System;
using System.Collections.Generic;
class JunkList
{
public string Resource { get; set; }
public string Junk { get; set; }
public int Amount { get; set; }
public JunkList(string r, string j, int a)
{
this.Resource = r;
this.Junk = j;
this.Amount = a;
}
}
class Program
{
static void Main(string[] args) // this is a method called "Main" . It is called when the program starts.
{
start:
string searchName;
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
Console.WriteLine("Which resource do you want to search for?? \n");
searchName = Console.ReadLine();
for (int i = 0; i < infoList.Count; i++)
{
if (infoList[i].Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
Console.WriteLine("Resource : " + infoList[i].Resource + "\n");
Console.WriteLine("Junk : " + infoList[i].Junk + "\n");
Console.WriteLine("Resource Amount : " + infoList[i].Amount + "\n");
}
else {
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
}
// wait for user to press a key. Then make an empty space and start over.
Console.ReadKey();
Console.WriteLine();
goto start; // go to start and run again
}
}
I recommend you to use 'single responsibility principle'. In your case that means that you should split your Main method into smaller methods. These methods do one simple action, i.e. responsibility.
Well, it will help:
You are right goto quite often is a bad practice (but not always). Put your code into while(true) and it would do the same but more clear. However, to close your application correctly receiving some char or key to exit would be better, e.g.
bool _runApplication = true;
while (_runApplication)
{
// code between "start:" and "goto start;"
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
To solve this multiple Resource Not found output you can separate searching by name and printing searching results, e.g.
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
foreach (var junkList in searchResult)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
where new method is:
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
It is because of searchName is equal to en empty string. Add a simple if to solve it.
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
Applying all these points you will get code like this (only Program class modified):
class Program
{
static void Main(string[] args)
{
bool _runApplication = true;
while (_runApplication)
{
List<JunkList> infoList = CreateJunkList();
Console.WriteLine("Which resource do you want to search for?? \n");
string searchName = Console.ReadLine();
List<JunkList> searchResult = GetJunkListsBySearchName(infoList, searchName);
if (searchResult.Count != 0)
{
PrintJunkLists(searchResult);
}
else
{
Console.WriteLine("Resource Not found <Press Enter to perform a new search>");
}
Console.WriteLine();
if (Console.Read() == 'x')
{
_runApplication = false;
}
}
}
private static List<JunkList> CreateJunkList()
{
List<JunkList> infoList = new List<JunkList>();
infoList.Add(new JunkList("Screw", "Type Writer", 2));
infoList.Add(new JunkList("Screw", "Clip Board", 1));
infoList.Add(new JunkList("Screw", "Toy Car", 3));
return infoList;
}
private static void PrintJunkLists(List<JunkList> junkLists)
{
foreach (var junkList in junkLists)
{
PrintJunkList(junkList);
}
}
private static void PrintJunkList(JunkList junkList)
{
Console.WriteLine("Resource : " + junkList.Resource + "\n");
Console.WriteLine("Junk : " + junkList.Junk + "\n");
Console.WriteLine("Resource Amount : " + junkList.Amount + "\n");
}
private static List<JunkList> GetJunkListsBySearchName(List<JunkList> infoList, string searchName)
{
List<JunkList> output = new List<JunkList>();
foreach (var junkList in infoList)
{
if (searchName.Length > 0 &&
junkList.Resource.ToLowerInvariant().Contains(searchName.ToLowerInvariant()))
{
output.Add(junkList);
}
}
return output;
}
}
I hope it helped)
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());
}
}
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.
I want to display if the Android "ServiceTestCase" Class is being used in any of the Directories.
The Program currently
1) Displays the Sensor Types the File uses
2) Displays the number of Implementations of the "onSensorChanged" Method
3) Displays the other functions that call the "onSensorChange" Implementation.
How do I display Classes?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ABB.SrcML;
using ABB.SrcML.Data;
using NUnit.Framework;
using System.Collections;
namespace CodeAnalysisToolkit
{
[TestFixture]
public class SimpleAnalyticsCalculator_Thesis
{
//------Test Case Class------------------------------------------------------------------------
[TestCase]
public void CalculateSimpleProjectStats()
{
int NumOfApps = 5;
//-----------Current Working Method to Get sub directories -------------------------
// Get list of files in the specific directory.
string[] TopDirectories = Directory.GetDirectories(#"C:\School\Grad School (Comp Sci)\Thesis\Apps\",
"*.*",
SearchOption.TopDirectoryOnly);
// Display all the files.
//for (int i = 0; i <= NumOfApps; i++)
//{
// Console.WriteLine(TopDirectories[i]);
//}
//Print out all Top Sub Directoies for Specified Path
//foreach (string file in TopDirectories)
//{
// Console.WriteLine(file);
//}
//----------End of Print Sub directory Method----------------------------------------
for (int i = 0; i < NumOfApps; i++)
{
var dataProject = new DataProject<CompleteWorkingSet>(TopDirectories[i],
Path.GetFullPath(TopDirectories[i]),
"..//..//..//SrcML");
Console.WriteLine();
Debug.WriteLine("#############################################");
Debug.WriteLine("Parsing " + TopDirectories[i]);
dataProject.UpdateAsync().Wait();
NamespaceDefinition globalNamespace;
Assert.That(dataProject.WorkingSet.TryObtainReadLock(5000, out globalNamespace));
DisplaySensorTypes(globalNamespace);
//DisplayWhetherAppIsUnitTested();
DisplayCallsToOnSensorChanged(globalNamespace);
}
}
//-------Display Sensor Type Class--------------------------------------------------------------
private void DisplaySensorTypes(NamespaceDefinition globalNamespace)
{
var getDefaultSensorCalls = from statement in globalNamespace.GetDescendantsAndSelf()
from expression in statement.GetExpressions()
from call in expression.GetDescendantsAndSelf<MethodCall>()
where call.Name == "getDefaultSensor"
select call;
foreach (var call in getDefaultSensorCalls)
{
if (call.Arguments.Any())
{
var firstArg = call.Arguments.First();
var components = firstArg.Components;
if (components.Count() == 3 &&
components.ElementAt(0).ToString() == "Sensor" &&
components.ElementAt(1).ToString() == ".")
{
Debug.WriteLine("sensor " + components.ElementAt(2).ToString() + " found");
}
}
}
}
private void DisplayWhetherAppIsUnitTested()
{
throw new NotImplementedException();
}
//-------Display Calls to OnSensorChanged Class------------------------------------------------
private void DisplayCallsToOnSensorChanged(NamespaceDefinition globalNamespace)
{
var senChangedMethods = from method in globalNamespace.GetDescendants<MethodDefinition>()
where method.Name == "onSensorChanged"
select method;
if (senChangedMethods.Count() == 0)
{
Debug.WriteLine("This File Does not contain any Sensor Change Mehtods");
}
else
{
Debug.WriteLine("----- ");
Debug.WriteLine("\r\n");
Debug.WriteLine(senChangedMethods.Count() + " Implementations of " + senChangedMethods.First().GetFullName());
Debug.WriteLine("----- ");
int n = senChangedMethods.Count();
for (int i = 0; i < n; i++)
{
var senChangedMethod = senChangedMethods.ElementAt(i);
Debug.WriteLine("Implementations of onSensorChaged # " + (i + 1) + ": " + senChangedMethod.GetFullName());
//"GetCallsToSelf" returns the number of times the number is called
var callsToSenChanged = senChangedMethod.GetCallsToSelf();
for (int j = 0; j < callsToSenChanged.Count(); j++)
{
var callerMethod = callsToSenChanged.ElementAt(j).ParentStatement.GetAncestorsAndSelf<MethodDefinition>();
if (callerMethod.Any())
{
Debug.WriteLine(" Called by --> " + callerMethod.ElementAt(0).GetFullName());
}
}
//Debug.WriteLine("----- ");
}
} //End of Else does not Equal 0 Check
}
//-------Display Test Class--------------------------------------------------------------
}
}