Hi folks!
Need some guidance here. We have our camera following our Player game object throughout the scene which is great.
If the Player game object is destroyed, we instantiate a new Player game object (as a prefab), and we need help making the camera find this new instantiated game object. Right now through debugging, we can’t figure out how to do this as it is saying our GameObject is null. Any advice would be greatly appreciated. Here’s some of our code:
FollowPlayer.cs
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
void Start()
{
offset = transform.position;
}
void Update()
{
if(player == null)
{
Debug.Log (player);
}
else
{
transform.position = player.transform.position + offset;
}
}
}
In GameController.cs, we wait for 3 seconds after the Player has been destroyed and then instantiate a new Player game object.
GameController.cs
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour
{
public GameObject player;
private bool gameOver;
private bool restart;
private Vector3 playerSpawn;
void Start()
{
playerSpawn = GameObject.Find("Player").transform.position;
gameOver = false;
restart = false;
}
void Update()
{
if(gameOver)
{
restart = true;
if(restart)
{
restart = false;
gameOver = false;
StartCoroutine(WaitForSeconds(3));
}
}
}
public void GameOver()
{
gameOver = true;
}
public void UpdatePlayerSpawn(Vector3 newPlayerSpawn)
{
playerSpawn = newPlayerSpawn + new Vector3(0, 1.0f, 0);
Debug.Log (playerSpawn);
}
IEnumerator WaitForSeconds (float duration)
{
yield return new WaitForSeconds (duration);
Instantiate(player, playerSpawn, player.transform.rotation);
}
}