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
TheBoxyBear2y 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
ero2y ago
you can put delegates outside of classes?
TheBoxyBear
TheBoxyBear2y ago
Like how you can have classes inside classes
ero
ero2y 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
canton72y 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
canton72y 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
canton72y 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
🩷🐻 𝙎𝙖𝙘𝙠𝙗𝙤𝙮 🐻🩷
Alright, thanks for answering! dogohappy