Search Unity

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

Discussion in 'Prefabs' started by Halficoding, Nov 9, 2019.

  1. Halficoding

    Halficoding

    Joined:
    Aug 16, 2019
    Posts:
    1
    Hello everyone :) I hope you have a great day! :D

    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 :
    Screenshot 2019-11-09 at 10.33.36.png

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

    have a wonderful day :)
     

    Attached Files:

  2. cristianm_unity

    cristianm_unity

    Unity Technologies

    Joined:
    Oct 16, 2018
    Posts:
    259
    Hi @Halficoding!

    You could try this:

    Code (CSharp):
    1. public void StartGame()
    2. {
    3.     GameObject newPlayer = Instantiate(player, position, rotation);
    4.     MyCustomData playerData = newPlayer.AddComponent<MyCustomData>();
    5.     playerData.Setup(value1, value2, value3);
    6.     DontDestroyOnLoad(newPlayer);
    7.     SceneManager.LoadScene("Scenes/GameScene");
    8. }
    1. Instantiate the new player.
    2. Add to that player a Component that will contain the data you want to pass.
    3. Call a method in that Component (e.g. Setup) passing to that method the data.
    4. Mark the new player as Don't Destroy On Load, so Unity will not destroy it when loading the new Scene.
    5. Load the new Scene.
    In your new Scene you will have a player with a component MyCustomData, with the data you passed.
     
    Last edited: Dec 30, 2019