Home > front end >  Find all active/inactive gameObjects that has common script attached
Find all active/inactive gameObjects that has common script attached

Time:09-29

I am trying to find all active and nonactive gameObjects which have a common script added to them. I am able to find all active gameObjects but unfortunately the inactive ones do not get viewed by my script. How can I overcome this?

public myScript[] commonScripts;

void Start() {
 commonScripts = FindObjectsOfType(typeof(myScript)) as myScript[];
}

CodePudding user response:

If myScript is one of your C# scripts, I'd use a static list containing all instances.

Sample Code

using System.Collections.Generic;
using UnityEngine;

public class MyScript : MonoBehaviour
{
    public static List<MyScript> allObjects = new List<MyScript>();

    private void Start()
    {
        if (allObjects.Contains(this) == false)
            allObjects.Add(this);
    }

    private void OnDestroy()
    {
        if (allObjects.Contains(this))
            allObjects.Remove(this);
    }
}

You can use this in any other class as follows

using UnityEngine;

public class AnotherScript : MonoBehaviour
{
    private void AnyFunction()
    {
        foreach (MyScript ms in MyScript.allObjects)
        {
            // do whatever you want
        }
    }
}

CodePudding user response:

You should try a different approach where the component instance adds itself to the list on Awake/Start

public class MyScript : MonoBehaviour
{
    void Awake()
    {
         FindObjectOfType<ContainerClass>().Add(this);
    }
    void OnDestroy()
    {
         FindObjectOfType<ContainerClass>().Remove(this);
    }
}

public class ContainerClass : MonoBehaviour
{
    private List<MyScript> scripts = new List<MyScript>();
    
    public void Add(MyScript script)
    {
         scripts.Add(script);
    }
    public void Remove(MyScript script)
    {
         scripts.Remove(script);
    }
}
  • Related