Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Can anyone explain to me, how to save "score" with PlayerPrefs and display it on the screen?
public class record : MonoBehaviour{
private Text counterText;
public float score;
void Start()
{
counterText = GetComponent<Text>() as Text;
}
void Update()
{
score += Time.deltaTime;
counterText.text = "Score: " + score.ToString("00");
}}
You can add 2 methods to your class
void SaveScore()
{
PlayerPrefs.SetFloat("score", score);
}
void LoadScore()
{
PlayerPrefs.GetFloat("score");
}
More informations about PlayerPrefs here: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
PlayerPrefs are stored in the system registry. It's not a good idea to use them to save the score, prefer a simple text file with encryption: (Stack Overflow, Unity Forum)
PlayerPrefs utility is use to store data permanently till the app installed on device. And types supported to store is limited, such as float, int, string. You can further use it, derive new methods using int and string, its up to you.
PlayerPrefs uses Key-Value structure, that means it will store a value (int, float, string) against a string key. For example I'd save high score against the key "highscore", and by the same string key I'd get back the stored value.
Now, to save score you can use
// To set high score
int scoreToSet = 140;
PlayerPrefs.SetInt("highscore", scoreToSet);
// To get high score
int scoreToGet = 0;
scoreToGet = PlayerPrefs.GetInt("highscore");
where "highscore" is the string key. Key must match in order to get and set values.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
What I want to achieve is to make sure that my property is always 0 or greater. The type doesn't matter.
Lets say:
var x = 3;
var y = 5;
And after x -= y x is supposed to be 0.
Currently using this way and was wondering of there is a way without member variables:
public int Coins
{
get { return Math.Max(0, _coins); }
set { _coins = value; }
}
Couldn't either figure out a way with uint.
All suggestions appreciated.
uint x = 3;
uint y = 5;
Expected x beeing 0 after x -= y but received unit max.
If you implement the get and set differ from the automatic properties, then you always need to declare a private member to store the value. This is by design.
Even if you use the automatic properties and don't declare the private member, the compiler will do it anyway. You just see less code, but the computer sees no differences.
Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
Anyway, I would suggest 1 small change:
public int Coins
{
get { return _coins; }
set { _coins = Math.Max(0, value); }
}
This way, the "wrong" _coins value don't get stored. But of course, it based on your bussiness logic, so the suggested code might not the right one for you
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
hey everyone
I asked this question in unity answers but I didn't get any answers.
I'm new to programming and I have a question about scriptable objects. I'm making a strategy management game and I have characters in the game with unique information like name, age, cloth, skills, and many more (+35 variables include int, strings, Lists, and GameObjects), I made a scriptable object for this purpose and read each character data from it and change them if needed.
firstly, I want to know is it logical to have 100+ characters with these scriptable objects attached to each one of them or just use a simple script for my character to handle variables.
secondly, make them from the start or instantiate them in the middle of the game which one is better?
thirdly, how about saving and using them in runtime?
Thanks
Edit:
After searching for answers finally, it is obvious that there is no need for scriptable objects for this type of variables and GameObjects. so I decided to update my question.
now my question is what is the best way to use this type of character variable? my characters heavily depend on stats and variables that need to change or read all of the time like stress of the character drop over time and needs to show always.
I use this simple, easy to edit and maintain method, which purists will probably poo-har, but it will get you running quick and easy. Put it all in your class constructor method, with a switch statement.
You set shared attributes outside, and specific attributes inside the switch statement.
Then you can create an NPC as easy as MyNpc = new NPC(16) Where 16 is Warrior type or whatever. Its easy to add new attributes at the top without editing 100 scriptable objects, you can see everything in one spot.
I've got five as an example, but you could have a 100 here without taking up much space. You can add one without doing any modifications.
You can create them at runtime.
public class NPC
{
public int NPC_ID; // the unique ID of the NPC
public string Name;
public bool active;
public string SpriteName;
public int PassiveAbility; // The passive ability the NPC grants 0= none
public int Dice_ID; // The Dice ID the NPC adds to the party 0=none
public int HP; // Max hit points (fully healed)
public int HPR; // Hit points remaining
public int FP; // Max food points
public int FPR; // food points remaining
public int MaxSlots; // Number of item slots
public bool Fem; // Use female audio
public NPC(int ID) // Pass the ID to create the NPC of that ID
{
NPC_ID = ID;
HP = 2;
PassiveAbility = 0;
MaxSlots = 3;
FP = 5;
Fem = false;
switch (ID)
{
case 1:
Name = "Bisky"; SpriteName = "N25"; PassiveAbility = 12; MaxSlots = 0; FP = 20; break;
case 2:
Name = "Zahid"; SpriteName = "N28"; PassiveAbility = 2; MaxSlots = 4; break;
case 3:
Name = "Anna"; SpriteName = "N17"; HP = 1; PassiveAbility = 3; FP = 8; Fem = true; break;
case 4:
Name = "Carl"; SpriteName = "N30"; PassiveAbility = 4; MaxSlots = 4; break;
case 5:
Name = "Max"; SpriteName = "N06"; PassiveAbility = 5; break;
default:
Debug.Log("ERROR: Got passed a bad NPC number: {NPC constructor}");
break;
}
HPR = HP; // Set current hit points to Max Hit points
FPR = FP; // Set current food points to Max Food points
}
} // End Class
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a grade calculator but I'm completely unsure how to compile the code to do so.
So far I've got the ability to split a user's response, but now I need to know how to take those splits and use them as separate values in order to create an average. I'm completely clueless how to achieve this and I've been searching for 2 days now on the internet with no luck.
Console.WriteLine ("User response seperated by commas goes here.");
string response = Console.ReadLine ();
Char delimiter = ',';
string[] splitResponses = response.Split (delimiter);
I need to know how to take those splits and use them as separate
values in order to create an average.
Not sure what you mean by take those splits and use them as separate
values, result is an array you could elements using index like splitResponseses[0]
To calculate the average you need to convert them to ints (or respective types), and calculate average.
string[] splitResponses = response.Split (delimiter); // Split string
int sum=0;
foreach(string s in splitResponses)
{
var valueInt = int.Parse(s); // convert string to an int.
sum+= valueInt;
}
double average = (double)sum/splitResponses.Length;
Another simple solution using Linq extensions.
int[] splitResponses = response.Split (delimiter) // Split string
.Select(int.Parse) // Convert To int value;
.ToArray();
Now you could calculate average using
splitResponses.Average(); // Average
splitResponses.Sum(); // Sum
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I finally found a code possibly working Shannon Entropy calculation, but as I don't fully understand C# at all, could someone help me fully grasp it please? I mean purely understand the code, NOT what it is doing. I do understand Delphi, if you ask.
public static double ShannonEntropy(string s)
{
var map = new Dictionary<char, int>();
foreach (char c in s)
{
if (!map.ContainsKey(c))
map.Add(c, 1);
else
map[c] += 1;
}
double result = 0.0;
int len = s.Length;
foreach (var item in map)
{
var frequency = (double)item.Value / len;
result -= frequency * (Math.Log(frequency) / Math.Log(2));
}
return result;
}
You have a function called ShannonEntropy which takes a string s and returns something of type double (basically a floating point number).
You instantiate a map (dictionary) of characters -> integers and call it map.
Loop over every character in the string s. During that loop check to see if the character is in our map (map). If it is not, map that character to 1. If it is already in the map, increment the value. At the end we'll have a map of each character to a count of how often it appears in s.
Declare a double name result and set it 0.
Declare an integer called len which is the length of the input string.
Loop over every character in our map. During the loop we're going to compute the frequency of how often it appears.
We declare a variable called frequency and set it to the count (the value we stored in the map) divided by the length of the string - so the frequency gets set to the percentage of each character that appears in s every time we loop.
Now we take the frequency (the percentage the given character appeared) and multiply it by the log (base 2) of the frequency, take the product and subtract it from result (which was initially 0).
Once we've finished looping we return the result.
Var is initializing variable map , new dictionary has added a dictionary to the var . dictionary gives the string or a char value an integer Value, let's say that red = 1 , blue = 2 , green = 3 etc . I think foreach runs the loop for as long as there there are char in string .
You must know if( ) it compiles the code only if the statement inside is true or false as in this case.math.log is a method . then at end we return result . I am not very familiar with c# I am more familiar with c and Java .
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I can run the program and fill in my inputs but get no output.No errors at all.
I am making an calculator that works by selecting radio buttons to select a mathematical function.
The answer must apear in the tbAntwoord but I cant get that working
Can somebody please help>? Its a school assignment and I am really new to this
private void buBereken_Click(object sender, EventArgs e)
{
//variabelen
double antwoord;
int x, y, graden;
//inlezen variabelen
antwoord = Convert.ToInt16(tbAntwoord.Text);
x = Convert.ToInt16(tbX.Text);
y = Convert.ToInt16(tbY.Text);
graden = Convert.ToInt16(tbGraden.Text);
// berekeningen
if (raDelen.Checked)
antwoord = x / y;
if (raMacht.Checked)
antwoord = Math.Pow(x, y);
if (raSin.Checked)
antwoord = (Math.Sin(graden));
if (raCos.Checked)
antwoord = (Math.Cos(graden));
tbAntwoord.Text = antwoord.ToString();
Console.Write("antwoord");
You are calculating a value and assigning it to a variable antwoord, but you are printing a string "antwoord" rather then the variable:
Console.Write( antwoord ) ;
Even then, if your application has no console (a text-only window), there will be nothing to see the output on.
You are also setting the Text property of tbAntwoord to a string representation of antwoord, but it is not demonstrated in the code what tbAntwoord is. For it to be displayed, it must refer perhaps to a object in the GUI form, or something else must specifically display it. It cannot be determined from this fragment alone what the problem is.