I am trying to make some buttons which change variables, so instead of writing new code every time I have to make a new button, I made a function which could do it for me.
The method "void buttons" has 4 arguments, but the "numberOF" argument does not work. When I clicked on the button, it was supposed to change arguement "numberOf" and "price", but it will never change "numberOf" for some reason.
Hopefully there is someone here that can help me. I know there is a lot of stuff I didn't use. I did the buttons with a long code every time when I tried this the first time, so there is some extraneous code still needing to be cleaned out.
using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour
{
public int one;
//Money
public int money;
//Iventory
public int stone;
public int jord;
public int frø;
public int korn;
public int brød;
//Item price
public int stonePrice;
public int jordPrice;
public int frøPrice;
public int kornPrice;
public int brødPrice;
//Item inventory text and button text
private string moneyText;
private string stoneText;
private string jordText;
private string frøText;
private string kornText;
private string brødText;
private string stoneButton;
private string jordButton;
private string frøButton;
private string kornButton;
private string brødButton;
//Screen heith/width = 0
private int screenWidth;
private int screenHeight;
// Runs one time
void Start ()
{
//Set variables to screen heith/width to 0
screenWidth = Screen.width - Screen.width;
screenHeight = Screen.height - Screen.height;
//Money reset
money = 10000;
//inventory reset
stone = 0;
jord = 0;
frø = 0;
korn = 0;
brød = 0;
//item price reset
stonePrice = 1;
jordPrice = 3;
frøPrice = 5;
kornPrice = 7;
brødPrice = 9;
//Set item text
moneyText = "money: " + money + " kr.";
stoneText = " stone " + stone;
jordText = " jord " + jord;
frøText = " frø " + frø;
kornText = " korn " + korn;
brødText = " brød " + brød;
//set button text
stoneButton = "Stone " + stonePrice + " kr.";
jordButton = "Jord " + jordPrice + " kr.";
frøButton = "Frø " + frøPrice + " kr.";
kornButton = "Korn " + kornPrice + " kr.";
brødButton = "Brød " + brødPrice + " kr.";
}
void Update ()
{
stone = stone;
jord = jord;
frø = frø;
korn = korn;
brød = brød;
moneyText = moneyText;
stoneText = stoneText;
jordText = jordText;
frøText = frøText;
kornText = kornText;
brødText = brødText;
//Check item text changes
moneyText = "money: " + money + " kr.";
stoneText = " stone " + stone;
jordText = " jord " + jord;
frøText = " frø " + frø;
kornText = " korn " + korn;
brødText = " brød " + brød;
//Check button text changes
stoneButton = "Stone " +stonePrice + " kr.";
jordButton = "Jord " + jordPrice + " kr.";
frøButton = "Frø " + frøPrice + " kr.";
kornButton = "Korn " + kornPrice + " kr.";
brødButton = "Brød " + brødPrice + " kr.";
}
void OnGUI ()
{
buttons(150, stoneButton, stone, stonePrice);
if (GUI.Button (new Rect (Screen.width - 100, Screen.height - 20, 100, 20), "End Turn"))
{
newRound();
}
//Iventory
GUI.TextArea (new Rect (screenWidth + 1, screenHeight + 2, Screen.width, 20),moneyText + " Inventory: " + stoneText + jordText + frøText + kornText + brødText);
}
void make_buttons(int position_heigth, string buttonText, int numberOF, int price)
{
GUI.TextArea (new Rect (screenWidth + 2, screenHeight + position_heigth + 80, 80, 20), buttonText);
if (GUI.Button (new Rect (screenWidth + 80, screenHeight + position_heigth + 80, 40, 20), "Buy"))
{
if (money > price)
{
numberOF = 1 + numberOF;
money = money - price;
}
else if (money == price)
{
numberOF = 1 + numberOF;
money = money - price;
}
}
if (GUI.Button (new Rect (screenWidth + 120, screenHeight + position_heigth + 80, 40, 20), "Sell"))
{
if (numberOF > 0)
{
numberOF = numberOF - 1;
money = money + price;
}
}
}
void newRound ()
{
stonePrice = stonePrice * 2;
jordPrice = jordPrice * 2;
frøPrice = frøPrice * 2;
kornPrice = kornPrice * 2;
brødPrice = brødPrice * 2;
}
}
I believe you are saying that the function does not modify the value of "numberOf".
This is not strictly true, however what you are doing is modifying a now local value. The reason for this is you are passing in an int, which is not passed by reference but rather by value.
You could probably correct this by modifying numberOf to ref numberOf, but I would actually recommend just returning numberOf if possible. It's more straight forward and clearer to understand what happened.
I would also recommend better variable and method names for buttons as it's not at ALL clear what action buttons is supposed to perform.
For further information on using ref arguments in C# this article is quite good.
Related
Basically, I am calibrating and applying offsets within unity. But the range of rotation isn't accurate and I'm wondering if its because of the wrong sensitivity application. I wanted help figuring out a way to stabilize the rotation as well as increase the range of rotation as it goes only form 0-90 and it shakes a lot.
Unity Code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class MPU6050_3 : MonoBehaviour
{
public GameObject target;
SerialPort stream = new SerialPort("COM3", 115200);
string[] accgyValues = new string[10];
int buffersize = 1000; //Amount of readings used to average, make it higher to get more precision but sketch will be slower (default:1000)
int acel_deadzone = 2; //Acelerometer error allowed, make it lower to get more precision, but sketch may not converge (default:8)
int giro_deadzone = 1; //Giro error allowed, make it lower to get more precision, but sketch may not converge (default:1)
float ax, ay, az, gx, gy, gz, gx_f, gy_f, gz_f;
float mean_ax, mean_ay, mean_az, mean_gx, mean_gy, mean_gz, state = 0;
float ax_offset = 0, ay_offset = 0, az_offset = 0, gx_offset = 0, gy_offset = 0, gz_offset = 0;
bool cal;
public float factor = 1;
public bool enableRotation;
public bool enableTranslation;
//float acc_normalizer_factor = 0.00025f;
float gyro_normalizer_factor = 1.0f/65.5f;
void Awake()
{
stream.Open();
//stream.ReadTimeout=50;
}
void Update()
{
if (state == 0)
{
accel();
Debug.Log("\nReading sensors for first time...");
state++;
Debug.Log("State is:"+state);
}
else if (state == 1)
{
Debug.Log("\nCalculating offsets...");
calibration();
state++;
Debug.Log("State is:" + state);
}
else if (state == 2)
{
accel();
Debug.Log("SensorW/Offset:" + mean_ax + ":" + mean_ay + ":" + mean_az + ":" + mean_gx + ":" + mean_gy + ":" + mean_gz);
Debug.Log("Offset:" + ax_offset + ":" + ay_offset + ":" + az_offset + ":" + gx_offset + ":" + gy_offset + ":" + gz_offset);
state++;
Debug.Log("State is:" + state);
}
else if (state == 3)
{
getaccgy();
//if (enableTranslation) target.transform.position = new Vector3(ax+ax_offset, az-az_offset, ay-ay_offset);
gx_f = (gx + gx_offset) * gyro_normalizer_factor;
gy_f = (gy + gy_offset) * gyro_normalizer_factor;
gz_f = -(gz + gz_offset) * gyro_normalizer_factor ;
if (enableRotation) target.transform.rotation = Quaternion.Euler(gx_f * factor, gz_f * factor, gy_f * factor);
Debug.Log("ValueRot "+ gx_f +" " + gy_f + " " + gz_f);
Debug.Log("State is:" + state);
}
}
public void getaccgy()
{
stream.Write("r");
Debug.Log("In accel");
string value;
accgyValues = new string[10];
value = stream.ReadLine();
accgyValues = value.Split(",");
ax = int.Parse(accgyValues[0]); //* acc_normalizer_factor;
ay = int.Parse(accgyValues[1]); //* acc_normalizer_factor;
az = int.Parse(accgyValues[2]); //* acc_normalizer_factor;
gx = int.Parse(accgyValues[3]); //* gyro_normalizer_factor;
gy = int.Parse(accgyValues[4]); //* gyro_normalizer_factor;
gz = int.Parse(accgyValues[5]); //* gyro_normalizer_factor;
Debug.Log("GetACCGY");
Debug.Log("SensorW/Offset:" + ax + ":" + ay + ":" + az + ":" + gx + ":" + gy + ":" + gz);
}
void accel()
{
float i = 0f, buff_ax = 0f, buff_ay = 0f, buff_az = 0f, buff_gx = 0f, buff_gy = 0f, buff_gz = 0f;
while (i < 1101)
{
getaccgy();
if (cal)
{
ax = ax + ax_offset;
ay = ay + ay_offset;
az = az + az_offset;
gx = gx + gx_offset;
gy = gy + gy_offset;
gz = gz + gz_offset;
}
if (i > 99 && i < (buffersize + 100))
{ //First 100 measures are discarded
buff_ax += ax;
buff_ay += ay;
buff_az += az;
buff_gx += gx;
buff_gy += gy;
buff_gz += gz;
}
if (i == (buffersize + 100))
{
mean_ax = buff_ax / buffersize;
mean_ay = buff_ay / buffersize;
mean_az = buff_az / buffersize;
mean_gx = buff_gx / buffersize;
mean_gy = buff_gy / buffersize;
mean_gz = buff_gz / buffersize;
Debug.Log("Mean:" + mean_ax + ":" + mean_ay + ":" + mean_az + ":" + mean_gx + ":" + mean_gy + ":" + mean_gz);
}
i++;
Debug.Log("Mean Sensor");
Debug.Log("Buffer Size is" + buffersize + "i mean" + i);
Debug.Log("SensorW/Offset:" + ax + ":" + ay + ":" + az + ":" + gx + ":" + gz);
}
}
void calibration()
{
cal = true;
Debug.Log("Callibration Entered");
ax_offset = -mean_ax / 8;
ay_offset = -mean_ay / 8;
az_offset = (16384 - mean_az) / 8;
gx_offset = -mean_gx / 4;
gy_offset = -mean_gy / 4;
gz_offset = -mean_gz / 4;
int ready = 0;
while (ready < 7)
{
//accelgyro.setXAccelOffset(ax_offset);
//accelgyro.setYAccelOffset(ay_offset);
//accelgyro.setZAccelOffset(az_offset);
//accelgyro.setXGyroOffset(gx_offset);
//accelgyro.setYGyroOffset(gy_offset);
//accelgyro.setZGyroOffset(gz_offset);
accel();
Debug.Log("..." + ready);
if (Math.Abs(mean_ax) <= acel_deadzone) ready++;
else ax_offset = ax_offset - mean_ax / acel_deadzone;
if (Math.Abs(mean_ay) <= acel_deadzone) ready++;
else ay_offset = ay_offset - mean_ay / acel_deadzone;
if (Math.Abs(16384 - mean_az) <= acel_deadzone) ready++;
else az_offset = az_offset + (16384 - mean_az) / acel_deadzone;
if (Math.Abs(mean_gx) <= giro_deadzone) ready++;
else gx_offset = gx_offset - mean_gx / (giro_deadzone + 1);
if (Math.Abs(mean_gy) <= giro_deadzone) ready++;
else gy_offset = gy_offset - mean_gy / (giro_deadzone + 1);
if (Math.Abs(mean_gz) <= giro_deadzone) ready++;
else gz_offset = gz_offset - mean_gz / (giro_deadzone + 1);
if (ready == 6) break;
}
}
}
Arduino Code:
Just a simple code to get the raw values:
// I2Cdev and MPU6050 must be installed as libraries
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
/////////////////////////////////// CONFIGURATION /////////////////////////////
//Change this 3 variables if you want to fine tune the skecth to your needs.
int buffersize=1000; //Amount of readings used to average, make it higher to get more precision but sketch will be slower (default:1000)
int acel_deadzone=8; //Acelerometer error allowed, make it lower to get more precision, but sketch may not converge (default:8)
int giro_deadzone=1; //Giro error allowed, make it lower to get more precision, but sketch may not converge (default:1)
// default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
//MPU6050 accelgyro;
MPU6050 accelgyro(0x68); // <-- use for AD0 high
int16_t ax, ay, az,gx, gy, gz;
int mean_ax,mean_ay,mean_az,mean_gx,mean_gy,mean_gz,state=0;
int ax_offset,ay_offset,az_offset,gx_offset,gy_offset,gz_offset;
/////////////////////////////////// SETUP ////////////////////////////////////
void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
Wire.begin();
// COMMENT NEXT LINE IF YOU ARE USING ARDUINO DUE
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz). Leonardo measured 250kHz.
// initialize serial communication
Serial.begin(115200);
// initialize device
accelgyro.initialize();
//wait for ready
//while (Serial.available() && Serial.read()); // empty buffer
//while (!Serial.available()){
//Serial.println(F("Send any character to start sketch.\n"));
//delay(1500);
//}
//while (Serial.available() && Serial.read()); // empty buffer again
}
// start message
//Serial.println("\nMPU6050 Calibration Sketch");
//delay(2000);
//Serial.println("\nYour MPU6050 should be placed in horizontal position, with package letters facing up. \nDon't touch it until you see a finish message.\n");
//delay(3000);
// verify connection
//Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
//delay(1000);
// reset offsets
//accelgyro.setXAccelOffset(0);
//accelgyro.setYAccelOffset(0);
//accelgyro.setZAccelOffset(0);
//accelgyro.setXGyroOffset(0);
//accelgyro.setYGyroOffset(0);
//accelgyro.setZGyroOffset(0);
void loop() {
if(Serial.available() > 0)
{
char ltr = Serial.read();
if(ltr == 'r')
{
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
Serial.print(ax);
Serial.print(",");
Serial.print(ay);
Serial.print(",");
Serial.print(az);
Serial.print(",");
Serial.print(gx);
Serial.print(",");
Serial.print(gy);
Serial.print(",");
Serial.println(gz);
Serial.flush();
}
}
}
I have, code who do for me "x + y = z"
if (command.Contains("+")) // string polecenie = "";'
{
polecenie = "{" + command + ")";
polecenie = polecenie.Replace("+", "}(");
double a = Convert.ToDouble(Between(polecenie, "{", "}"));
double b = Convert.ToDouble(Between(polecenie, "(", ")"));
double wyn = a + b;
richTextBox1.Text += a + " + " + b + " is " + wyn + "\r\n";
}
And when 'command' is "4+5","3 + 4" or something like this code works, but when i try to do "4 + 3 + 23" it don't work. Final string with starting 'command' "4+5+6", polecenie is: "{4}(5}(6)"... The Between Method:
public string Between(string content, string First, string Last)
{
string end = "";
int Plc1 = content.IndexOf(First) + First.Length;
int Plc2 = content.IndexOf(Last);
end = content.Substring(Plc1, Plc2 - Plc1);
return end;
}
How can I do that? (I want it to work with all possible additions ("4+4","34+5+54","43+4+65+54"...)
You could use the DataTable object to not re-invent the wheel.
richTextBox1.Text = string.Format("{0} is {1}\r\n", command,
(new System.Data.DataTable()).Compute(command, string.Empty));
This would support +, -, *, / and % (mod) operators. For more: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx
First let me present the code:
private void AdicionarFormula(string x, string y, string Materia)
{
MessageBox.Show("%" + x + " = " + y + "#" + Materia);
StreamWriter Escritor = new StreamWriter(Properties.Settings.Default.ArquivoDeFormulas, true);
Escritor.WriteLine("%" + x + " = " + y + "#" + Materia);
Escritor.Close();
LerFormulas(true);
}
The issue is: instead of the output being "%x = y#Materia" it is actually "
%x = y
#Materia"
I dont want it to create a new line for "#Materia".
Your parameter 'y' contains char a newline. For example, try it in your code:
string.Format("%" + x + " = " + y + "#" + Materia).Replace("\n","")
I am making the game minesweeper and I am trying to implement a highScores feature. I am trying to load 3 different files (each one holds the high scores for each of the 3 difficulty settings) into 3 different richTextBox's. When I run the app and click the 'high scores' tab from the menu strip it works the first time. However if I play a game and then try to access the high scores form I get an Exception error -
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
'C:\Users\jzcon_000\Copy\Visual
Studio\Projects\Assignment1\Assignment1\bin\Debug\highScoresMed.txt'
because it is being used by another process
This is where the call is made
private void highScoresToolStripMenuItem_Click(object sender, EventArgs e)
{
Minesweeper.HighSc highScore = new Minesweeper.HighSc();
highScore.read();
highScore.Show();
}
This is the method in my HighSc class
public void read()
{
StreamReader readerE = File.OpenText("highScoresEasy.txt");
StreamReader readerM = File.OpenText("highScoresMed.txt");
StreamReader readerH = File.OpenText("highScoresHard.txt");
if (readerE != null)
{
string readEasy = File.ReadAllText("highScoresEasy.txt");
richTextBox1.Text = readEasy;
}
readerE.Close();
if (readerM != null)
{
string readMed = File.ReadAllText("highScoresMed.txt");
richTextBox2.Text = readMed;
}
readerM.Close();
if (readerH != null)
{
string readHard = File.ReadAllText("highScoresHard.txt");
richTextBox3.Text = readHard;
}
readerH.Close();
}
Heres the save high scores class
namespace Minesweeper
{
class Save
{
int diff, hr, min, sec;
string player;
public Save(int difficulty, int hour, int minute, int second, string playerN)
{
diff = difficulty;
hr = hour;
min = minute;
sec = second;
player = playerN;
}
public void save()
{
StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true);
StreamWriter writerMed = new StreamWriter("highScoresMed.txt", true);
StreamWriter writerHard = new StreamWriter("highScoresHard.txt", true);
if (diff == 1)
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerEasy.Close();
}
else if (diff == 2)
{
writerMed.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerMed.Close();
}
else if (diff == 3)
{
writerHard.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerHard.Close();
}
}
}
}
So when you have the difficulty level set to 1 and then save, you open the StreamWriters for both the level2 and level3 but never close them.
This could only mean that when you try to load the highscore for these two levels you will find your files locked by your previous save.
You should change your Save method to open only the required file
public void save()
{
if (diff == 1)
{
using(StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true))
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
}
}
else if (diff == 2)
....
else if (diff == 3)
....
I suggest also to use the using statement in your reading method to be sure that also in case of exceptions the stream are correctly disposed
I have found plenty of information on how to look at physical drives but I need to monitor several mount points on my physical drives. I would prefer to do this through wmi but any .NET objects that could do it would be fine as well.
So I figured this one out finally. With WMI its a constant battle against poor documentation and just figuring out this stuff on your own.
RESOURCES
wbemtest for testing your queries
wbemtest reference
scriptomatic for generating wmi scipts in several languages
scriptomatic
The code:
using System;
using System.IO;
using System.Management;
using System.Diagnostics;
namespace Monitor
{
class Program
{
static void Main(string[] args)
{
double Free, Size, FreePercentage;
DateTime Now = DateTime.Now;
string scopeStr = string.Format(#"root\cimv2", "TestSqlServer");
ManagementScope scope = new ManagementScope(scopeStr);
scope.Connect();
string queryString = "SELECT * FROM Win32_Volume WHERE DriveLetter IS NULL";
SelectQuery query = new SelectQuery(queryString);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
Console.WriteLine("Entering Volume loop: ");
foreach (ManagementObject disk in searcher.Get())
{
Console.WriteLine("foreach Volume: ");
//-------------------------------------------------------------------------
//Console.WriteLine("Free %" + double.Parse(disk["FreeSpace"].ToString()) / double.Parse(disk["Capacity"].ToString()) * 100);
FreePercentage = double.Parse(disk["FreeSpace"].ToString()) / double.Parse(disk["Capacity"].ToString()) * 100;
//-------------------------------------------------------------------------
string _MountPoint = disk["Name"].ToString();
//Console.WriteLine("Free: " + disk["FreeSpace"].ToString());
Free = Math.Round(Convert.ToDouble(disk["FreeSpace"]) / (1024 * 1024), 2);
Console.WriteLine("Free: " + Free + " MB");
//Console.WriteLine("Capacity: " + disk["Capacity"].ToString());
Size = Math.Round(Convert.ToDouble(disk["Capacity"]) / (1024 * 1024), 2);
Console.WriteLine("Size: " + Size + " MB");
if (_MountPoint[_MountPoint.Length - 1] == Path.DirectorySeparatorChar)
{
_MountPoint = _MountPoint.Remove(_MountPoint.Length - 1);
}
_MountPoint = _MountPoint.Replace("\\", "\\\\\\\\");
string _MountPointQueryString = "select * FROM Win32_MountPoint WHERE Directory=\"Win32_Directory.Name=\\\"" + _MountPoint + "\\\"\"";
SelectQuery _MountPointQuery = new SelectQuery(_MountPointQueryString);
using (
ManagementObjectSearcher mpsearcher =
new ManagementObjectSearcher(scope, _MountPointQuery))
{
Console.WriteLine("Entering directory Foreach loop: ");
foreach (ManagementObject mp in mpsearcher.Get())
{
Console.WriteLine("Foreach directory: ");
try
{
//Console.WriteLine("Volume: " + mp["Volume"].ToString());
Console.WriteLine("Directory: " + mp["Directory"].ToString());
string Volume = mp["Directory"].ToString().Replace("Win32_Directory.Name=", "");
if (FreePercentage <= 5.00)
{
throw new Exception("\nLabel: " + Volume + "\nSeverity: " + EventLogEntryType.Error + "\nTime: " + Now + "\nMessage: disk space threshhold: " + CalculateUsedSpace(Free, Size) + " % used (" + Free + "MB" + " free)");
}
}
catch (Exception ex)
{
EventLog.WriteEntry("DriveStats Warning", "Message: " + ex.Message, EventLogEntryType.Error);
}
}
}
}
}
}
static double CalculateUsedSpace(double f, double s)
{
double UsedPercentage;
if (s == 0)
{
return f;
}
else if (s >= 0 && f == 0)
{
UsedPercentage = 100.00;
return UsedPercentage;
}
else
{
double UsedSpace = s - f;
UsedPercentage = (UsedSpace / s) * 100;
UsedPercentage = Math.Round(UsedPercentage, 2);
//Console.WriteLine("Used Percentage: " + UsedPercentage);
return Math.Round(UsedPercentage, 2);
}
}
static double CalculateFreePercentage(double f, double s)
{
double FreePercentage;
if (f == 0)
{
FreePercentage = 0;
return FreePercentage;
}
else
{
FreePercentage = (f / s) * 100;
//Console.WriteLine("Free Percentage: " + FreePercentage);
return Math.Round(FreePercentage, 2);
}
}
}
}