How to make a permanent variable in C# [duplicate] - 2d

This question already has answers here:
Saving/loading data in Unity
(1 answer)
How to pass data (and references) between scenes in Unity
(6 answers)
Closed 1 year ago.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
float playerScore = 0;
float highScore1 = 0;
public Text scoreText;
public Text highScore;
void start ()
{
highScore.text = highScore1.ToString();
}
float Update(){
playerScore += Time.deltaTime*15;
scoreText.text = playerScore.ToString("0");
if (playerScore >= highScore1)
{
highScore1 = playerScore;
highScore.text = highScore1.ToString();
}
else
{
highScore.text = highScore1.ToString();
}
return highScore1;
}
}
I wanted to make a game that measures the time you stay alive and then displays it as a score. I also wanted to make a high score. I used this code for making it but it keeps resetting each time I restart the game. How can I make it permanent?

Related

Unity 3D script player shoot bad direction

I'm using Unity 3d version 4 because I have a MacOS X and I'm making a FPS 3D
I have a script to make the player shoot but this script only shoots up and does not consider where I point the mouse
Below the code in CS
Could someone please correct my script because I have been blocked for 3 days and I have not found any solution on the Internet. Thanks
using UnityEngine;
using System.Collections;
public class ShootDemo : MonoBehaviour {
public Rigidbody projectile;
public float speed = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
Rigidbody instantiatedProjectile = Instantiate(projectile,
transform.position,
transform.rotation)
as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
}
}
The way you set the velocity is not right, you should get the mouse position like this:
Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, transform.rotation);
var input = Input.mousePosition;
input.z = 10;
Vector2 touchPos = Camera.main.ScreenToWorldPoint(input);
Vector2 dir = new Vector2(transform.position.x, transform.position.y) - touchPos;
dir.Normalize();
instantiatedProjectile.velocity = dir * speed;
I found this script in JavaSript working but the bullet speed is too slow and then the bullet stays in the scene for 2 seconds instead of making it disappear completely. How can I then add strength to the bullet?
var Effect : Transform;
var TheDamage = 100;
function Update ()
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast (ray, hit, 100))
{
var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particleClone.gameObject, 2);
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
}

Implementing own TileServerProvider

I am using HERE Maps SDK Lite Edition Version 4.7.3.0, which gives the possibility to ad a RasterLayer with an own TileServerProvider implementation (see documentation).
I edited the given example by exchanging the SimpleTileServerProvider with my own implementation.
RasterLayer myCustomLayer = new RasterLayer("CUSTOM_LAYER",
17,
1001,
new TileServerProvider() {
#NonNull
#NotNull
#Override
public String provideURL(long x, long y, long zoom) {
return "myURI";
}
});
When adding this RasterLayer to my MapView, provideURI is called, but only 0 values are passed to the parameters of provideURI. What is getting wrong here?
In my production code I did not enter 17 for parameter maxZoomLevel directly, but took this value from a function. But this function did return 0 instead.
I am glad to help you.
To load custom Raster layers, the format of the URL should be as follows:
https://YourRasterTileService.com/zoom/xTile/yTile.png.
I am successfully able to load the Custom Raster with the example you have mentioned in the Here documentation link.
String myCustomRasterLayerName = "my_custom_raster_layer";
long maxZoom = 19;
long drawOrder = 1000;
TileServerProvider staticTileServerProvider = new SimpleTileServerProvider("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png");
RasterLayer rasterLayer = new RasterLayer(
myCustomRasterLayerName,
maxZoom,
drawOrder,
staticTileServerProvider);
mapSceneConfig = new MapSceneConfig();
mapSceneConfig.rasterLayers.add(rasterLayer);
mapSceneConfig.customMapLayers.put(myCustomRasterLayerName, LayerState.ENABLED);
mapView.getMapScene().loadScene(MapStyle.EMPTY, mapSceneConfig, new MapScene.LoadSceneCallback() {
#Override
public void onLoadScene(#Nullable MapScene.ErrorCode errorCode) {
if (errorCode != null) {
Log.d(TAG, "onLoadScene failed: " + errorCode.toString());
}
}
});
If you would like me to investigate further specific to your code implementation of TileServerProvider, please share the code implementation integrated in one of the sample app downloadable from the below link.
https://github.com/heremaps/here-sdk-examples/tree/master/examples/latest/lite/android/MapOverlaysLite

Unity 5 2D make coins move towards player

I have written a script that I have attached to Player which upon collecting a Magnet Power-Up, finds all the active GameObjects with a tag Treasure and makes them follow Player.
The thing is that I want all the active Treasure GameObjects not to only follow but actually go towards and collide with the Player so that points are collected.
Below is my code so far, any help is appreciated.
using UnityEngine;
using System.Collections;
public class TreasureFollowPlayer : MonoBehaviour {
public GameObject[] treasures;
public bool magnetPowerUpEnabled = false;
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Magnetpowerup"))
{
col.gameObject.SetActive(false);
magnetPowerUpEnabled = true;
}
}
// Update is called once per frame
void Update() {
if (magnetPowerUpEnabled)
{
treasures = GameObject.FindGameObjectsWithTag("Treasure");
foreach (var treasure in treasures)
{
treasure.transform.position = Vector2.MoveTowards(treasure.transform.position, transform.position, 1.0f * Time.deltaTime);
}
}
}
}
You will need to ensure the treasure moves faster than the player so it can catch up for starters. Then have a small script either on the treasure or the player which checks for onTriggerEnter calls. When the treasure touches the player then fire off a function destroying or disabling it and increase the players score however is appropriate.

change text based on button-click

I am using Unity3d
I've tried to track where the problem comes from and had no success. The text update in "Guess" occurs properly when done by key press, but no by clicking the button (both log in an exception).
The code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour
{
public Text guessText;
int min;
int max;
int guess;
public void Higher ()
{
min = guess;
NextGuess ();
}
public void Lower ()
{
max = guess;
NextGuess ();
}
public void Correct ()
{
print ("I won!");
StartGame ();
}
private void StartGame ()
{
min = 1;
max = 1000;
guess = 500;
guessText.text = guess.ToString();
print (guess);
}
private void NextGuess ()
{
guess = (max + min) / 2;
guessText.text = guess.ToString();
print (guess);
}
// Use this for initialization
void Start ()
{
StartGame ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.UpArrow)) {
Higher ();
} else if (Input.GetKeyDown (KeyCode.DownArrow)) {
Lower ();
} else if (Input.GetKeyDown (KeyCode.Return)) {
Correct ();
}
}
}
By the way, I've put the buttons on another controller called "LevelManager". I've added [RequireComponent(typeof(LevelManager))] above class declaration, but it didn't work.
Basically, it says that in guessText.text = guess.ToString(); object is not set to an instance, but I've set in Unity3d that the particular text is referenced and that it should use NumberWizard.cs
When you create this script it need to be attached to a GameObject. As you have done the coding it should be attached to an Empty gameObject. Then when you select the script from editor your public variable Text guessText will be available on the edior, Now you have to drag and drop the GUIText you have created on to the guessText property.
The error says that you have to initialize the variable, whether by doing a "new" or asingning it to a ingame drag'n'drop object as Dinal says.

How to deal with Number precision in Actionscript?

I have BigDecimal objects serialized with BlazeDS to Actionscript. Once they hit Actionscript as Number objects, they have values like:
140475.32 turns into 140475.31999999999998
How do I deal with this? The problem is that if I use a NumberFormatter with precision of 2, then the value is truncated to 140475.31. Any ideas?
This is my generic solution for the problem (I have blogged about this here):
var toFixed:Function = function(number:Number, factor:int) {
return Math.round(number * factor)/factor;
}
For example:
trace(toFixed(0.12345678, 10)); //0.1
Multiply 0.12345678 by 10; that gives us 1.2345678.
When we round 1.2345678, we get 1.0,
and finally, 1.0 divided by 10 equals 0.1.
Another example:
trace(toFixed(1.7302394309234435, 10000)); //1.7302
Multiply 1.7302394309234435 by 10000; that gives us 17302.394309234435.
When we round 17302.394309234435 we get 17302,
and finally, 17302 divided by 10000 equals 1.7302.
Edit
Based on the anonymous answer below, there is a nice simplification for the parameter on the method that makes the precision much more intuitive. e.g:
var setPrecision:Function = function(number:Number, precision:int) {
precision = Math.pow(10, precision);
return Math.round(number * precision)/precision;
}
var number:Number = 10.98813311;
trace(setPrecision(number,1)); //Result is 10.9
trace(setPrecision(number,2)); //Result is 10.98
trace(setPrecision(number,3)); //Result is 10.988 and so on
N.B. I added this here just in case anyone sees this as the answer and doesn't scroll down...
Just a slight variation on Frasers Function, for anyone who is interested.
function setPrecision(number:Number, precision:int) {
precision = Math.pow(10, precision);
return (Math.round(number * precision)/precision);
}
So to use:
var number:Number = 10.98813311;
trace(setPrecision(number,1)); //Result is 10.9
trace(setPrecision(number,2)); //Result is 10.98
trace(setPrecision(number,3)); //Result is 10.988 and so on
i've used Number.toFixed(precision) in ActionScript 3 to do this: http://livedocs.adobe.com/flex/3/langref/Number.html#toFixed%28%29
it handles rounding properly and specifies the number of digits after the decimal to display - unlike Number.toPrecision() that limits the total number of digits to display regardless of the position of the decimal.
var roundDown:Number = 1.434;
// will print 1.43
trace(roundDown.toFixed(2));
var roundUp:Number = 1.436;
// will print 1.44
trace(roundUp.toFixed(2));
I converted the Java of BigDecimal to ActionScript.
We had no choices since we compute for financial application.
http://code.google.com/p/bigdecimal/
You can use property: rounding = "nearest"
In NumberFormatter, rounding have 4 values which you can choice: rounding="none|up|down|nearest". I think with your situation, you can chose rounding = "nearest".
-- chary --
I discovered that BlazeDS supports serializing Java BigDecimal objects to ActionScript Strings as well. So if you don't need the ActionScript data to be Numbers (you are not doing any math on the Flex / ActionScript side) then the String mapping works well (no rounding weirdness). See this link for the BlazeDS mapping options: http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=serialize_data_2.html
GraniteDS 2.2 has BigDecimal, BigInteger and Long implementations in ActionScript3, serialization options between Java / Flex for these types, and even code generation tools options in order to generate AS3 big numbers variables for the corresponding Java ones.
See more here: http://www.graniteds.org/confluence/display/DOC22/2.+Big+Number+Implementations.
guys, just check the solution:
protected function button1_clickHandler(event:MouseEvent):void
{
var formatter:NumberFormatter = new NumberFormatter();
formatter.precision = 2;
formatter.rounding = NumberBaseRoundType.NEAREST;
var a:Number = 14.31999999999998;
trace(formatter.format(a)); //14.32
}
I ported the IBM ICU implementation of BigDecimal for the Actionscript client. Someone else has published their nearly identical version here as a google code project. Our version adds some convenience methods for doing comparisons.
You can extend the Blaze AMF endpoint to add serialization support for BigDecimal. Please note that the code in the other answer seems incomplete, and in our experience it fails to work in production.
AMF3 assumes that duplicate objects, traits and strings are sent by reference. The object reference tables need to be kept in sync while serializing, or the client will loose sync of these tables during deserialization and start throwing class cast errors, or corrupting the data in fields that don't match, but cast ok...
Here is the corrected code:
public void writeObject(final Object o) throws IOException {
if (o instanceof BigDecimal) {
write(kObjectType);
if(!byReference(o)){ // if not previously sent
String s = ((BigDecimal)o).toString();
TraitsInfo ti = new TraitsInfo("java.math.BigDecimal",false,true,0);
writeObjectTraits(ti); // will send traits by reference
writeUTF(s);
writeObjectEnd(); // for your AmfTrace to be correctly indented
}
} else {
super.writeObject(o);
}
}
There is another way to send a typed object, which does not require Externalizable on the client. The client will set the textValue property on the object instead:
TraitsInfo ti = new TraitsInfo("java.math.BigDecimal",false,false,1);
ti.addProperty("textValue");
writeObjectTraits(ti);
writeObjectProperty("textValue",s);
In either case, your Actionscript class will need this tag:
[RemoteClass(alias="java.math.BigDecimal")]
The Actionscript class also needs a text property to match the one you chose to send that will initialize the BigDecimal value, or in the case of the Externalizable object, a couple of methods like this:
public function writeExternal(output:IDataOutput):void {
output.writeUTF(this.toString());
}
public function readExternal(input:IDataInput):void {
var s:String = input.readUTF();
setValueFromString(s);
}
This code only concerns data going from server to client. To deserialize in the other direction from client to server, we chose to extend AbstractProxy, and use a wrapper class to temporarily store the string value of the BigDecimal before the actual object is created, due to the fact that you cannot instantiate a BigDecimal and then assign the value, as the design of Blaze/LCDS expects should be the case with all objects.
Here's the proxy object to circumvent the default handling:
public class BigNumberProxy extends AbstractProxy {
public BigNumberProxy() {
this(null);
}
public BigNumberProxy(Object defaultInstance) {
super(defaultInstance);
this.setExternalizable(true);
if (defaultInstance != null)
alias = getClassName(defaultInstance);
}
protected String getClassName(Object instance) {
return((BigNumberWrapper)instance).getClassName();
}
public Object createInstance(String className) {
BigNumberWrapper w = new BigNumberWrapper();
w.setClassName(className);
return w;
}
public Object instanceComplete(Object instance) {
String desiredClassName = ((BigNumberWrapper)instance).getClassName();
if(desiredClassName.equals("java.math.BigDecimal"))
return new BigDecimal(((BigNumberWrapper)instance).stringValue);
return null;
}
public String getAlias(Object instance) {
return((BigNumberWrapper)instance).getClassName();
}
}
This statement will have to execute somewhere in your application, to tie the proxy object to the class you want to control. We use a static method:
PropertyProxyRegistry.getRegistry().register(
java.math.BigDecimal.class, new BigNumberProxy());
Our wrapper class looks like this:
public class BigNumberWrapper implements Externalizable {
String stringValue;
String className;
public void readExternal(ObjectInput arg0) throws IOException, ClassNotFoundException {
stringValue = arg0.readUTF();
}
public void writeExternal(ObjectOutput arg0) throws IOException {
arg0.writeUTF(stringValue);
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
We were able to reuse one of the available BigDecimal.as classes on the web and extended blazeds by sublassing from AMF3Output, you'll need to specify your own endpoint class in the flex xml files, in that custom endpoint you can insert your own serializer that instantiates an AMF3Output subclass.
public class EnhancedAMF3Output extends Amf3Output {
public EnhancedAMF3Output(final SerializationContext context) {
super(context);
}
public void writeObject(final Object o) throws IOException {
if (o instanceof BigDecimal) {
write(kObjectType);
writeUInt29(7); // write U290-traits-ext (first 3 bits set)
writeStringWithoutType("java.math.BigDecimal");
writeAMFString(((BigDecimal)o).toString());
} else {
super.writeObject(o);
}
}
}
as simple as that! then you have native BigDecimal support using blazeds, wooohoo!
Make sure your BigDecimal as3 class implements IExternalizable
cheers, jb
Surprisingly the round function in MS Excel gives us different values then you have presented above.
For example in Excel
Round(143,355;2) = 143,36
So my workaround for Excel round is like:
public function setPrecision(number:Number, precision:int):Number {
precision = Math.pow(10, precision);
const excelFactor : Number = 0.00000001;
number += excelFactor;
return (Math.round(number * precision)/precision);
}
If you know the precision you need beforehand, you could store the numbers scaled so that the smallest amount you need is a whole value. For example, store the numbers as cents rather than dollars.
If that's not an option, how about something like this:
function printTwoDecimals(x)
{
printWithNoDecimals(x);
print(".");
var scaled = Math.round(x * 100);
printWithNoDecimals(scaled % 100);
}
(With however you print with no decimals stuck in there.)
This won't work for really big numbers, though, because you can still lose precision.
You may vote and watch the enhancement request in the Flash PLayer Jira bug tracking system at https://bugs.adobe.com/jira/browse/FP-3315
And meanwhile use the Number.toFixed() work-around see :
(http://livedocs.adobe.com/flex/3/langref/Number.html#toFixed%28%29)
or use the open source implementations out there : (http://code.google.com/p/bigdecimal/) or (http://www.fxcomps.com/money.html)
As for the serialization efforts, well, it will be small if you use Blazeds or LCDS as they do support Java BigDecimal serialization (to String) cf. (http://livedocs.adobe.com/livecycle/es/sdkHelp/programmer/lcds/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=serialize_data_3.html)
It seems more like a transport problem, the number being correct but the scale ignored. If the number has to be stored as a BigDecimal on the server you may want to convert it server side to a less ambiguous format (Number, Double, Float) before sending it.

Resources