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
TheBoxyBearโ€ข3y 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
eroโ€ข3y ago
you can put delegates outside of classes?
TheBoxyBear
TheBoxyBearโ€ข3y ago
Like how you can have classes inside classes
ero
eroโ€ข3y ago
i haven't been using them at all lol i've never seen a use for them
โ“๐™Œ๐™ช๐™š๐™จ๐™ฉ๐™ž๐™ค๐™ฃ ๐™ˆ๐™–๐™ง๐™ โŽโงน\
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
canton7โ€ข3y 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
โ“๐™Œ๐™ช๐™š๐™จ๐™ฉ๐™ž๐™ค๐™ฃ ๐™ˆ๐™–๐™ง๐™ โŽโงน\
Do you mean public delegates inside a class? So I should put them in a namespace like in the 1st line?
canton7
canton7โ€ข3y ago
Yes Nested means defined inside another type
โ“๐™Œ๐™ช๐™š๐™จ๐™ฉ๐™ž๐™ค๐™ฃ ๐™ˆ๐™–๐™ง๐™ โŽโงน\
// 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
canton7โ€ข3y 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

Did you find this page helpful?