The issue I am having is when I instantiate my enemy into the scene, the enemy is meant to start following the player, however when they spawn, the player game object, becomes unassigned in the inspector.
When I bring the prefab back into the scene and assign it myself the players transform position myself without deleting the enemy it works fine, and the enemy starts to follow the player, but basically as soon as its instantiated, the players transform is unassigned in the inspector.
Thank you if your able to help!
`public class SpawnManager : MonoBehaviour
{
public GameObject enemyPrefab;
public GameObject playerPrefab;
private float startDelay = 2;
private float repeatRate = 2;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnEnemy", startDelay, repeatRate);
}
// Update is called once per frame
void Update()
{
}
void SpawnEnemy()
{
Instantiate(enemyPrefab, new Vector3(0f, 0f, 50f), enemyPrefab.transform.rotation);
}
}
public class EnemyScript : MonoBehaviour
{
// Wheel Collider Fields
[SerializeField] WheelCollider FLWC;
[SerializeField] WheelCollider FRWC;
[SerializeField] WheelCollider BLWC;
[SerializeField] WheelCollider BRWC;
// Wheel Transform fields
[SerializeField] Transform FLW;
[SerializeField] Transform FRW;
[SerializeField] Transform BLW;
[SerializeField] Transform BRW;
// Public Variables
public float motorTorque = 100f;
public float maxSteering = 20f;
public Transform centerOfMass;
public Transform player;
public float speed = 4f;
// Private Variables
private Rigidbody carRb;
private Rigidbody enemyRb;
// Start is called before the first frame update
void Start()
{
enemyRb = GetComponent<Rigidbody>();
carRb = GetComponent<Rigidbody>();
carRb.centerOfMass = centerOfMass.localPosition;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 pos = Vector3.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
enemyRb.MovePosition(pos);
transform.LookAt(player);
WheelRotation();
}
private void WheelRotation()
{
var pos = Vector3.zero;
var rot = Quaternion.identity;
FLWC.GetWorldPose(out pos, out rot);
FLW.position = pos;
FLW.rotation = rot;
FRWC.GetWorldPose(out pos, out rot);
FRW.position = pos;
FRW.rotation = rot * Quaternion.Euler(0, 180, 0);
BLWC.GetWorldPose(out pos, out rot);
BLW.position = pos;
BLW.rotation = rot;
BRWC.GetWorldPose(out pos, out rot);
BRW.position = pos;
BRW.rotation = rot * Quaternion.Euler(0, 180, 0);
}
}
`