Platu Dev diary #1: Player persist across scenes

Posted by Dewald Bodenstein

Welcome to our first developer diary, a first for me as developer and our first for Platu. This will be like a quick tutorial. I'm sure it can be helpful to more people out there.

We are building Platu in the Unity game engine and one of the first things that we needed to get working was the simple thing of keeping the same player object instance across our Unity scenes or levels. So according to many forum posts we placed the following in the player controller script's Start() function:

DontDestroyOnLoad (gameObject);

That did solve the problem but, in testing, it also caused another issue. Games usually have many scenes and to test a specific scene you would place a player object in it to easily test from that point. So the problem comes in when you go from one scene, the first one, to the next, the second one, and the second one already has a player object in it. Now we have two conflicting player objects in the second scene because of the solution we used above.

To get around this, what we did was to save the player object as a prefab, remove it from our scenes and create a new object with a small script called PlayerStart. Firstly, the PlayerStart script keeps a variable to the player prefab and then in its Start() function we check if the player already exists using the FindObjectOfType function. If we could not find a player instance we instantiate the prefab. Finally, now that we are sure that we have a player, we place it at the same position as this PlayerStart object.

public GamePlayer player_prefab;

void Start () {
    GamePlayer player = GameObject.FindObjectOfType ();
		
    if (!player) {
        player = (GamePlayer)Instantiate(player_prefab,start_position,transform.rotation);
    }

    Player.transform.position = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
}

We can still add some more functionality to this. What if we want to return to the first scene? With this script you'll get placed right where you started. Wouldn't you rather want to get placed at the spot where you first transitioned from the first scene to the second one? For now, I'll leave that up to you to figure out.

comments powered by Disqus

Related Game

Platu