At the begin of my script, I do:
void InstantiateTargets(int amount)
{
var i = 0;
while (i <= amount-1) {
Instantiate (targetPrefab, new Vector3 (0, -100, 0), Quaternion.identity).name = "target"+i;
i++;
}
}
and
void AssignTargets()
{
targets = GameObject.FindGameObjectsWithTag("target");
Debug.Log(targets[0]); // comment 1
}
To illustrate my problem, I put this in the Update void:
void Update()
{
Debug.Log(targets[0]); // comment 2
}
Later on, I destroy all the targets, and AFTER that, I call both voids again. The weird thing is that comment 1 keeps working: it gives me the correct target. But the moment I destroy the targets, comment 2 gives me null
, even after I called the voids again to instantiate them again. The targets exists in the hierarchy, but I can’t use them using targets
.
Any thoughts what’s going on? What am I doing wrong here? Thanks a bunch!
Perhaps something like this:
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Assets.Scripts
{
public class DataHandler : MonoBehaviour
{
[SerializeField]
private GameObject targetPrefab;
public List<GameObject> Targets = new List<GameObject>();
/// <summary>
/// Create new targets.
/// </summary>
/// <param name="amount"></param>
public void InstantiateTargets(int amount)
{
for (int i=0; i < amount; i++)
{
var obj = Instantiate(targetPrefab, new Vector3(0, -100, 0), Quaternion.identity);
obj.name = "target" + i;
// Add target to list
Targets.Add(obj);
}
}
/// <summary>
/// Destroy one target.
/// </summary>
/// <param name="target"></param>
public void DestroyTarget(GameObject target)
{
var instanceId = target.GetInstanceID();
target = Targets.FirstOrDefault(f => f.GetInstanceID() == instanceId);
if (target != null)
{
Targets.Remove(target);
Destroy(target);
}
}
/// <summary>
/// Destroy multiple targets.
/// </summary>
/// <param name="targets"></param>
public void DestroyTargets(IEnumerable<GameObject> targets)
{
foreach (var target in targets)
{
// Get unique gameobject id
var instanceId = target.GetInstanceID();
var targetHolder = Targets.FirstOrDefault(f => f.GetInstanceID() == instanceId);
if (targetHolder != null)
{
Targets.Remove(targetHolder);
Destroy(targetHolder);
}
}
}
}
}