C
C#3y ago
?

delegate inside our outside class?

delegate void ADelegate(); // here?
public class PlayerShip : MonoBehaviour
{
delegate void ADelegate(); // or here?
event ADelegate DelegateHandler;
}
delegate void ADelegate(); // here?
public class PlayerShip : MonoBehaviour
{
delegate void ADelegate(); // or here?
event ADelegate DelegateHandler;
}
Should I create a delegate inside or outside a class? Is there a difference?
11 Replies
TheBoxyBear
TheBoxyBear3y ago
Being inside a class, you can give it more access modifiers But unless accessing it from the declaring class, you'll need the full name PlayerShip.ADelegate
ero
ero3y ago
you can put delegates outside of classes?
TheBoxyBear
TheBoxyBear3y ago
Like how you can have classes inside classes
ero
ero3y ago
i haven't been using them at all lol i've never seen a use for them
?
?OP3y ago
They are useful. It's like a redirect or a shortcut to piece of code, a pointer to particular methods Yeah, I know when it's inside a class and when I want to use it from other class I use class name dot variable name e.g. System.Random or UnityEngine.Random I was asking though if there is a difference if I put a delegate outside class, like in the 1st line
canton7
canton73y ago
It's the same as declaring a class inside another class, vs directly in a namespace The general advice is not to have public nested types, and that includes delegates and enums So avoid public nested delegates
?
?OP3y ago
Do you mean public delegates inside a class? So I should put them in a namespace like in the 1st line?
canton7
canton73y ago
Yes Nested means defined inside another type
?
?OP3y ago
// PlayerShip.cs
delegate void ADelegate();
public class PlayerShip : MonoBehaviour
{
internal delegate void BDelegate();
}


// OtherShip.cs
public class OtherShip : MonoBehaviour
{
ADelegate habazi = () => Debug.Log("");
PlayerShip.BDelegate wdwds = () => Debug.Log("");
}
// PlayerShip.cs
delegate void ADelegate();
public class PlayerShip : MonoBehaviour
{
internal delegate void BDelegate();
}


// OtherShip.cs
public class OtherShip : MonoBehaviour
{
ADelegate habazi = () => Debug.Log("");
PlayerShip.BDelegate wdwds = () => Debug.Log("");
}
Okay, so I guess this is the only difference? Different way of accessing them?
canton7
canton73y ago
Yeah, pretty much. The other is that nested types can be private/protected, which can be handy. That's the one time I would nest one
?
?OP3y ago
Alright, thanks for answering! dogohappy
Want results from more Discord servers?
Add your server