Working on an asteroid like game, when my ship gets hit it blows up and I Instantiate a new ship and surround it with a shield for a few seconds. While the ship is surrounded by the shield I disable collisions for a few seconds. This all works. After a few seconds I hide shield (SetActive(false)) and then set playerCollider.enabled = true. The shield hides but the collider will not re-enable.
code for when killed
public void KilledWaitTime()
{
SetLivesText();
Instantiate(player); //respawns player after killed
shield.SetActive(true);
playerCollider.enabled = false; //disables collider while shield up.
Debug.Log("collider = " + playerCollider.name);
Debug.Log("player = " + player.name);
Invoke("RemoveShields", 3);
}
code for removing shield and re-enabling collider
public void RemoveShields()
{
shield.SetActive(false);
// Collider pc = player.GetComponent<Collider>();
Debug.Log("collider pc = " + playerCollider.name);
Debug.Log("player pc = " + player.name);
playerCollider.enabled = true;
}
When you call Instantiate(player);
, you are creating a completely separate object from the previous player object. When you instantiate the player object, you need to re-assign playerCollider
to refer to the collider on the newly created object.
You also may want to keep your player prefab and your current player objects separate:
private GameObject playerPrefab;
private GameObject player;
public void KilledWaitTime()
{
SetLivesText();
player = Instantiate(playerPrefab); //respawns player after killed
playerCollider = player.GetComponent<Collider>();
shield.SetActive(true);
playerCollider.enabled = false; //disables collider while shield up.
Debug.Log("collider = " + playerCollider.name);
Debug.Log("player = " + player.name);
Invoke("RemoveShields", 3);
}