How to instantiate a new player object, in another scenes, after having bought weapons in a shop ?

Hello everyone :slight_smile: I hope you have a great day! :smile:

Today, I have a little problem I’ve been struggling with for weeks : I’m trying to create a game where you start with a Weapon Shop UI with upgrades, you have let’s say 500 points, then you pick a weapon (for example, a shotgun) then the points get decremented by say 250 points, and you pick bonus speed for 100 points. After that, you click on a Start button, then the game scene loads, with the new data in game.

How would you achieve that ?

I mean, I would like to Instantiate a player sprite (a circle) with the new datas, but I don’t understand how to switch scenes properly, with instantiating the player, WITH the new data loaded…

I’ve studied the source code of someone’s project to try and implement this, but I don’t know how to put it in my game actually… I mean, why instantiating a new player object while setting playerUI to true in the same time ? Because, for me, first of all, it instantiate a player prefab in the shop, + it makes the playerUI visible (so that I have 2 players).
I tried to put a start button, with on click, switching scenes + triggering the StartGame() below, but it doesn’t instantiate the player in the new scene and gives me 2 sprites of the player (with playerUI…)

here’s a part of the code :

If you have a good way to achieve this, please let me know :smile:

have a wonderful day :slight_smile:

5157281--510920--image.png

Hi @Halficoding !

You could try this:

public void StartGame()
{
    GameObject newPlayer = Instantiate(player, position, rotation);
    MyCustomData playerData = newPlayer.AddComponent<MyCustomData>();
    playerData.Setup(value1, value2, value3);
    DontDestroyOnLoad(newPlayer);
    SceneManager.LoadScene("Scenes/GameScene");
}
  • Instantiate the new player.
  • Add to that player a Component that will contain the data you want to pass.
  • Call a method in that Component (e.g. Setup) passing to that method the data.
  • Mark the new player as Don’t Destroy On Load, so Unity will not destroy it when loading the new Scene.
  • Load the new Scene.

In your new Scene you will have a player with a component MyCustomData, with the data you passed.