Other
Check transform changes on multiple GameObjects / re-instantiate script on existing GameObject
I have a Manager object to which I attach a script that listens to transform changes on multiple GameObjects in the scene.
The script works fine on the first instantiation on the Manager and when the GameObjects it listens to are instantiated for the first time. But after I destroy the GameObjects and re-instantiate a new set of GameObjects to listen to, I can't reset the script's public variables, so the Update() method is still listening to destroyed GameObjects within the obsolete dictionary.
using UnityEngine;
using System.Collections.Generic;
public class InteractionManager : MonoBehaviour
{
private Dictionary<GameObject, Vector3> _interactables;
public void Awake()
{
_interactables = new Dictionary<GameObject, Vector3>();
}
private void appendGO (GameObject gO)
{
gO.transform.hasChanged = false; // prevent initial update
_interactables.Add(gO, gO.transform.position);
Debug.Log("NEW interaction tracking for GameObject: " + gO.name);
}
public void addGO( GameObject gO )
{
if( !_interactables.ContainsKey(gO) )
{
appendGO(gO);
}
else{
print("Already listening to Object " + gO.name);
}
}
public void reset()
{
_interactables.Clear();
}
public void Update()
{
// BUG: public variables are not updated, can Add but not Remove
List<GameObject> keys = new List<GameObject>(_interactables.Keys);
foreach(GameObject gO in keys)
{
// when GameObjects are destroyed
if( gO == null)
{
print("Object reference missing");
continue;
}
// detect changes to objects transform
if (gO.transform.hasChanged)
{
Debug.Log("The transform has changed!");
gO.transform.hasChanged = false;
}
}
}
}
I've read on some other threads that we can simply destroy the Manager's script component and re-instantiate it. But when I do that, it stops calling the Update() method altogether.
I've also tried serialization, but it didn't change anything in my context.
Is there anything I missed out ? I'm running out of ideas.
I just saved the object name instead of its reference, so I'm finding the object at each call of Update()