float and int on player prefs
Hello ı aim to save the highscore to player prefs when the score is higher than current highscore here is my codeand the errors i get. Thanks in advance
Assets/Scripts/Score.cs(43,45): error CS1502: The best overloaded method match for UnityEngine.PlayerPrefs.SetInt(string, int)' has some invalid arguments Assets/Scripts/Score.cs(43,45): error CS1503: Argument
#2' cannot convert float' expression to type
int'
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Score : MonoBehaviour
{
public Text scoreText;
public Text endGame;
public Text saniye;
public float myTimer = 0.0f;
public float life;
public Text highScoreText;
public float highScore = 0;
string highScoreKey = "HighScore";
void Start()
{
scoreText = GetComponent<Text>();
endGame.text = "";
saniye.text = "";
highScore = PlayerPrefs.GetInt(highScoreKey,0);
}
void Update()
{
life = healthBar.cur_health;
if (life > 0) {
myTimer += Time.deltaTime;
Debug.Log("life < 0");
scoreText.text = Mathf.Round(myTimer).ToString();
}
if (life < 0) {
Debug.Log("life < 0");
endGame.text = Mathf.Round(myTimer).ToString();
scoreText.text = "";
saniye.text ="Secs Alive";
if(myTimer>highScore){
PlayerPrefs.SetInt(highScoreKey, myTimer);
PlayerPrefs.Save();
}
}}
}
Answer by mujpir · Sep 24, 2015 at 10:19 AM
You are setting int to float . You have to convert float to int.
PlayerPrefs.SetInt(highScoreKey, (int) myTimer);
Also , Why not using PlayerPrefs.SetFloat to save a float value like time? This way you don't need to cast your type:
PlayerPrefs.SetFloat(highScoreKey, myTimer);
var timer = PlayerPrefs.GetFloat(highScoreKey);
Hello mujpir,
"PlayerPrefs.SetInt(highScore$$anonymous$$ey, (int) myTimer);" this worked well thanks alot.
Of course it "works" with a cast, but you should keep in $$anonymous$$d that when casting a float to an int you loose precision. For example a value of "5.78" would become simply "5" as an int can only hold integer numbers (whole numbers). So it would be better to use "PlayerPrefs.SetFloat" like mujpir said.
Your answer

Follow this Question
Related Questions
Google play services? 0 Answers
need script for launching missile 0 Answers
Acceleration issue 0 Answers
Unity Scripting Learn 1 Answer