I’m working through Challenge 4 - Soccer Scripting - Unity Learn task 7 to get enemies to move towards players goal. I’ve added the player goal in the inspector. The scripts I’m using is this.
public class EnemyX : MonoBehaviour
{
public float speed;
private Rigidbody enemyRb;
public GameObject playerGoal;
// Start is called before the first frame update
void Start()
{
enemyRb = GetComponent<Rigidbody>();
playerGoal = GameObject.Find("PlayerGoal");
}
// Update is called once per frame
void Update()
{
// Set enemy direction towards player goal and move there
Vector3 lookDirection = (playerGoal.transform.position - transform.position).normalized;
enemyRb.AddForce(lookDirection * speed);
}
private void OnCollisionEnter(Collision other)
{
// If enemy collides with either goal, destroy it
if (other.gameObject.name == "Enemy Goal")
{
Destroy(gameObject);
}
With this script the enemies won’t move unless the player hits them then its random slow movement. I get an error message saying “NullReferenceException: Object reference not set to an instance of an object” which I assume means I haven’t added the player goal into the inspector. But I have, but when I press play it disappears.
If I delete the " playerGoal = GameObject.Find(“PlayerGoal”);" from the start the first enemy moves towards goal as it should but then the next wave of enemies don’t move and the inspector area goes blank. I have put it so prefabs behave same way as origional enemy.
If I double click the error message it highlights this line.
Vector3 lookDirection = (playerGoal.transform.position - transform.position).normalized;