The function will be called a lot in an SO asset, it contains function implementations for every Button in the game which I’ll assign from the inspector. Just experimenting, so I don’t have to look at dozens of places to change a button behavior.
I was rather asking about implementation specifics, like…How does the code look like that makes actual use of the delegate? I mean, if these methods are already defined in that SO, and you set buttons in the inspector, you could just register the listeners programmatically for the onClick event.
public void BackToMainMenu()
{
if( GetActiveSceneName() != "Main" )
LoadSceneDelegate("Main");
else
{
DisplayMainMenu();
}
}
public void OpenInventory()
{
int x = -271;
int y = 400;
SetCameraPosition(x,y);
if (GetActiveSceneName() == "Victory")
LoadSceneDelegate("Main");
}
public void OpenEquipment()
{
int x = 758;
int y = 400;
SetCameraPosition(x, y);
if (GetActiveSceneName() == "Victory")
LoadSceneDelegate("Main");
}
[...]
I want to avoid referencing these buttons in code. At runtime I’ll not complain if it doesn’t find a button.
By making it a delegate you just basically gave the method an object identity. Which means it could be null, or point to a completely different method all together that also takes a string.
Where as the ‘LoadScene’ method will specifically call SceneManager.LoadScene.
I will say though… is there a reason you can’t just call SceneManager.LoadScene in your code?
Why can’t you do this?
public void OpenEquipment()
{
int x = 758;
int y = 400;
SetCameraPosition(x, y);
if (GetActiveSceneName() == "Victory")
SceneManager.LoadScene("Main");
}
I mainly ask… because if you need to ask this question about delegates. You probably don’t know what a delegate really is. And honestly… if someone was in my garage and picked up my ‘hoozit’ and said “can I use this to change my oil?” my first question would be “what makes you think that should be used to change oil?”
Well… I can think of a ton of reasons to use delegates. For one I just wrapped up creating my new input system built around delegates.
Not one of them is to save myself one less word and dot though.
Especially since you’ve increased computational overhead and memory (if only by a tiny amount). It’s often considered code smell if you’re creating runtime objects to save your self development/pre-compile time syntax.
… if you REALLY want to have that shortcut though. If you’re using the latest unity and you’re targeting .net 4.6, then you can access the ‘using static’ directive:
This will inline static methods to that *.cs file.
You must be targeting .net 4.6 since it’s a C#6 feature.
Just stick this at the top of the file next to your other using directives:
using static UnityEngine.SceneManagement.SceneManager;
But I’ll repeat myself… if typing “SceneManager.” is excruciating to you… you got a lot more issues coming ahead.