Lately in my Unity projects, I have discovered that to create a more modular application it helps to have a static List in a class that contains references to all or some of the objects created so that they may be accessed easily from other parts of the program. An example is below:
private static List<Canvas> availableCanvases = new List<Canvas>();
void Start () {
availableCanvases.Add(this);
}
public static void AddComponentToCanvas(Transform component) {
for (int i = 0; i < availableCanvases; i++) {
//Make sure the canvas still exists
if (availableCanvases[i] != null) {
component.SetParent(availableCanvases[i]);
return;
} else {
availableCanvases.RemoveAt(i);
i--;
}
}
//Reached if no canvas found
//Create new canvas or create error etc...
}
This simply allows an object that is instantiated at runtime to add itself to an available canvas without needing to access it through a findWithTag or findWithType method which will hurt performance if used too much.
Is this bad practice or good? My colleague reckons this represents singleton programming but it of course doesn't because it allows multiple objects to exist and be used.
availableCanvases
ever benull
? – RelativeavailableCanvases
is essentially acting as a singleton within the scope of the containing class, not the items that are contained inavailableCanvases
. – Whelp