I want enemy moving from point a to point b, and after reaching point b this enemy will be deleted. Works almost fine, enemies are moving ect. but i see this:
MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at :0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at :0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at :0)
WaveSpawner.SpawnEnemy () (at Assets/Scripts/WaveSpawner.cs:39)
WaveSpawner+d__6.MoveNext () (at Assets/Scripts/WaveSpawner.cs:32)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at :0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
WaveSpawner:Update() (at Assets/Scripts/WaveSpawner.cs:19)
After that enemies stops spawning. Enemies spawned earlier moves correctly, but after reaching its destination same error appear.
Enemy code:
using System.Diagnostics;
using UnityEngine;
public class BasicEnemy : MonoBehaviour {
public float speed = 10f;
private Transform target;
private int wavepointIndex = 0;
void Start()
{
target = Waypoints.points[0];
}
void Update()
{
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.4f)
{
GetNextWaypoint();
}
}
void GetNextWaypoint()
{
if (wavepointIndex >= Waypoints.points.Length - 1)
{
Destroy(gameObject);
return;
}
wavepointIndex++;
target = Waypoints.points[wavepointIndex];
}
}
And code for spawning enemies:
using UnityEngine;
using System.Collections;
public class WaveSpawner : MonoBehaviour {
public Transform enemyPrefab;
public Transform spawnPoint;
public float timeBetweenWaves = 5f;
private float countdown = 2f;
private int waveIndex = 0;
void Update ()
{
if (countdown <= 0f)
{
StartCoroutine(SpawnWave());
countdown = timeBetweenWaves;
}
countdown -= Time.deltaTime;
}
IEnumerator SpawnWave ()
{
waveIndex++;
for (int i = 0; i < waveIndex; i++)
{
SpawnEnemy();
yield return new WaitForSeconds(0.5f);
}
}
void SpawnEnemy ()
{
Instantiate(enemyPrefab, spawnPoint.position, spawnPoint.rotation);
}
}
I’m new at unity, so please explain why it should be done other way. Thanks, and i hope your eyes still exist after my english…