Search Unity

Help with properly deleting GetComponent and restarting a level. (infinite runner c#)

Discussion in 'Scripting' started by LucioMaximo, Dec 4, 2014.

  1. LucioMaximo

    LucioMaximo

    Joined:
    Dec 3, 2014
    Posts:
    10
    Hi,

    When my game restarts after the first playthrough, two versions of the player appear. The stats are kept, but the player is not properly de-spawned in between the end of the last round and the new round. The object is initialised in the Start method:

    void Start () {

    playerPhysics = GetComponent<PlayerPhysics> ();

    }

    When I want to restart my level (keeping stats from the player), my understanding is that you have to delete the GetComponent that you have created (which I do here):

    Destroy(gameObject.GetComponent("PlayerPhysics"));
    Application.LoadLevel ("SideSpikeSlice");

    From what I understand this as, the object is deleted, and then the level is restarted. In the Awake() method, I call
    DontDestroyOnLoad (this);

    in order to keep my stats between restarts of the level. Is this causing the problem? I have tried another variety of ways of invoking Destroy() on PlayerPhysics, and none have the desired effect of keeping the stats through the round reset, but re-initializing the player.

    Thanks

    Lucio
     
  2. GetUpKidAK

    GetUpKidAK

    Joined:
    Apr 9, 2013
    Posts:
    84
    GetComponent returns the component of the type on the gameObject it's called on, it doesn't initialise or create anything. The call in Start() just finds the PlayerPhysics component on the object this script is attached to.

    I'd suggest creating a class that stores the info you want to keep and make sure that doesn't get destroyed between scene changes. You can update this info when the player dies and then reload the scene without having to delete and reinstantiate the player.