I am working on a plugin. I need to detect from a Manager type script if any gameobject is instantiated in the scene at runtime. I also need to grab the newly instantiated gameobject. Without adding any script in the prefab.
Like this: FixedUpdate(){
if ( AnObjectInstantiated() ) {
GrabTheInstantiatedGO();
DoSomething();
}
If it’s possible for you to change the code that instantiates the objects, you could write your own go-between instantiate method that also calls event, then have whatever you need to know about new objects subscribe to that event. E.g.
public static class ExtensionMethods
{
public delegate void SpawnAction(Object newObj);
public static event SpawnAction OnSpawn;
public static Object SpawnObject(Object obj, Vector3 position, Quaternion rotation)
{
Object newObj = MonoBehaviour.Instantiate(obj, position, rotation);
if (OnSpawn != null)
OnSpawn(newObj);
return newObj;
}
}
public class SomeComponent : MonoBehaviour
{
void OnEnable()
{
ExtensionMethods.OnSpawn += ObjectSpawned;
}
void OnDisable()
{
ExtensionMethods.OnSpawn -= ObjectSpawned; // Prevent memory leaks by cleaning up event subscription
}
void ObjectSpawned(Object newObj)
{
Debug.Log("Object was spawned: " + ((GameObject) newObj).name);
}
}
Then, rather than use Instantiate() to spawn objects you want to track, use ExtensionMethods.SpawnObject()
I should note that I am still learning a lot myself…so there might be some catches to this method I don’t know about.
Without deeper methods being uncovered, the somewhat rude solution would be to compare the list of active objects with what the list of active objects used to be. The difference is anything new.
Keep in mind that both of these are performance heavy, so using them every fixedupdate would be significantly costly, and isn’t recommended.
This is obviously much faster and cheaper if you do have access to the scripts within the project.