- Home /
Empty scripts to avoid drag and drop?
Hello everyone,
Is it a bad practice (or is it just bad really) to create empty scripts just to use FindObjectsOfType() and have a convenient way of getting ALL the "type" in the scene without manually draggin and dropping them each time.
It would look something like that
using System.Collections.Generic;
using UnityEngine;
public class ChallengesLockingManager : MonoBehaviour
{
HashSet<Challenge_Button> buttons = null;
void Awake()
{
buttons = new HashSet<Challenge_Button>();
foreach(Challenge_Button button in FindObjectsOfType<Challenge_Button>())
{
buttons.Add(button);
}
}
}
with "Challenge_Button" and empty script as such
using UnityEngine;
public class Challenge_Button : MonoBehaviour
{
}
Answer by Bieere · Aug 11, 2019 at 04:31 PM
Yeah I wouldn't use the script solely for finding all of the objects of that Type.
What I would recommend though is used the ContextMenu attribute to call a function on the script you're looking to have that list on.
List<Challenge_Button> buttons = null;
[ContextMenu("Find all Challenge_Button ")]
private void FindAll()
{
buttons = FindObjectsOfType<Challenge_Button>().ToList();
}
Then you have to Right-click the component that you are using this script on, and it should appear in the dropdown menu.
Answer by sacredgeometry · Aug 11, 2019 at 06:51 PM
Its not really bad and given that you cant have multiple tags on objects I would say its as good a way as any other but I would steer clear of using Find and instead maybe adding items to a static readonly collection or singleton.
Because as the docs say:
Please note that this function is very slow. It is not recommended to use this function every frame. In most cases you can use the singleton pattern instead.
This way you have super quick lookup of the objects and you can iterate over them if you need to.
Maybe something like this:
Example
public static Dictionary<Guid, MyObject> Cache { get; private set; } = new Dictionary<Guid, MyObject>();
private Guid Id = Guid.NewGuid();
void Awake()
{
Cache.Add(Id, this);
}
void OnDestroy()
{
Cache.Remove(Id);
}
Your answer
Follow this Question
Related Questions
Detecting and setting active a child object using VRTK 0 Answers
Scripted SetTextureOffset not working after switching to Universal Render Pipeline 1 Answer
How to have an enemy spawn a certain distance behind the player 1 Answer
Application.isPlaying returning true when I exit play mode 0 Answers
Rotate object only on player input 0 Answers