1
\$\begingroup\$

I am making an 2D platformer for mobile in unity with c#. Right now it is setup in a way that I have one joystick that controls the players shooting, arm rotation and movement. But on that joystick there is an event trigger which is what I use to make the player shoot the gun when the joystick is pressed. The problem I am having is when the player dies the script in the event trigger disappears and I am no longer able to shoot. I am calling Destory() when the player dies and he does have lives. the location of that script is on the player I am not sure if that has anything to do with it but of anybody has any suggestions that would be great.

Here is the code for when the player dies and respawns

public static void KillPlayer (Player player)
{
    Destroy (player.gameObject);
    _remaningLives -= 1;
    if (_remaningLives <= 0)
    {

        gm.EndGame();

    }else
    {
        gm.StartCoroutine(gm._RespawnPlayer());
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Are you calling Destroy() on the player? \$\endgroup\$ Apr 20, 2017 at 3:52
  • \$\begingroup\$ Thanks for the reply! I really appricate it! Yes I am caling Destroy() when the player dies. the player does have lives and when he dies he losses a life and respawns and when he respawns the scripts in the event trigger disappear. I will add the code for when the player dies and respawns. \$\endgroup\$
    – Cole.C
    Apr 21, 2017 at 0:43

1 Answer 1

1
\$\begingroup\$

When you call Destroy() on the player, that also destroys the script your trying to access.

Instantiating a new copy isn't sufficient, as it's a new copy the old reference is pointing to the wrong place.

You have to update the reference when you instantiate the new copy:

_RespawnPlayer() {
    //...other code
    GameObject newPlayer = Instantiate(...);
    joystick.playerScriptRef = newPlayer.GetComponent<PlayerScript>();
    //...other code
}

(I don't know what your script names are called, you'll have to massage it yourself).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .