It looks like you're new here. If you want to get involved, click one of these buttons!
So, I am making a game similar to the game called 'Idle Balls', how do I store the position of all the ball image gameobjects so that when the player closes and reopens the app, the balls are still there? The balls are a 2D image with the 2D rigidbody component and are instantiated from an original image of the ball. Any help is greatly appreciated. I tried using playerprefs but it would be time consuming to make a playerpref for each axis and position of each of the balls, especially if there were hundreds of balls. I would appreciate links and samples of code if applicable.
Answers
It actually isnt as time consuming as you think.
Just add a script to the ball prefab you are instantiating the add these methods
void Load() //this goes in the start method
{
if(PlayerPrefs.GetFloat("x")!=null)
{
transform.position = new Vector2(PlayerPrefs.GetFloat("x"), PlayerPrefs.GetFloat("y"));
}
}
void save() // this goes in the Update method
{
PlayerPrefs.SetFloat("x", transform.position.x);
PlayerPrefs.SetFloat("y", transform.position.y);
}
@Sugar_Snail
Okay, thanks for the quick response! I will try it out!
@Sugar_Snail
It is not working for me... is this script correct?
using UnityEngine;
public class Ball : MonoBehaviour
{
public float xballcoords;
public float yballcoords;
void Start()
{
xballcoords = PlayerPrefs.GetFloat("x" + this.gameObject.name, 2.5f);
yballcoords = PlayerPrefs.GetFloat("y" + this.gameObject.name, 5.5f);
gameObject.transform.position = new Vector2(xballcoords, yballcoords);
}
void Update()
{
xballcoords = gameObject.transform.position.x;
yballcoords = gameObject.transform.position.y;
PlayerPrefs.SetFloat("x" + this.gameObject.name, xballcoords);
PlayerPrefs.SetFloat("y" + this.gameObject.name, yballcoords);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "DestroyBalls")
{
Destroy(gameObject);
}
}
}
you cant put the plus for the name i dont think
It works. I just have no idea how to instantiate them at the awake function.