Reputation: 148
(I want to make a 2d game with unity)
I would like to pass the coin values from the first scene to the second one.
I would like to take the coins from the first scene and set them as start point for the second scene,
Can someone explain me how it works via serialize?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CoinFinal : MonoBehaviour
{
// Für die Coinanzeige
public float coins = 1;
public Text CoinsAnzeige;
public GameObject house;
void Start()
{
CoinsAnzeige.text = coins.ToString();
house.SetActive(false);
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("coinblock"))
coins++;
}
void Update()
{
CoinsAnzeige.text = " " + coins.ToString();
if (coins > 9)
{
house.SetActive(true);
}
}
}
Found a Way:
void Start()
{
CoinTest = PlayerPrefs.GetInt("myScore");
}
void Update()
{
CoinUebergabe.text = PlayerPrefs.GetInt("myScore").ToString();
}
Upvotes: 0
Views: 187
Reputation: 515
As mentioned already you could use static variables. Another way would be to save the information in the PlayerPrefs
and load it from them again. A maybe less dirty way would be DontDestroyOnLoad
. even though I mentiond this two ways I think a Class with static attributes would be the best.
Upvotes: 1
Reputation: 453
This concept could be easily handled typically as "GameManager". Singleton
Here's the code I usually use:
Create empty gameobject in hierarchy window and attach this script:
public class GameManager : MonoBehaviour
{
public float coins;
private static GameManager _instance;
public static GameManager Instance
{
get
{
return _instance;
}
}
private void Awake()
{
if (_instance != null)
{
Destroy(gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
now you can access to your public properties at any time for example:
GameManager.Instance.coins = 3;
Upvotes: 2