Get a Node's Parent By Type with Godot C# Extension Methods, Generics and Recursion
Polysthetic
Using C# extension methods and generics to write a simple recursive method that returns the first parent of a given type/class for a node. I found this method to be very useful where I know a certain parent exists (usually a manager class or a kinematic body) but the scene hierarchy can change, breaking static references.
ā±ļø Timestamps: 0:00 Intro 1:05 Getting parent references with built in functions 2:45 Creating a static utilities class for the extension method 3:40 Writing the Get Parent of Type Node extension method 5:30 Casting the parent node to its type 6:00 Using recursion 7:21 Testing 8:53 Conclusion
š» Addenda:
- Note that Godot generally encourages a "call down, signal up" architecture where parent nodes connect signals amongst their children, and call down on their child methods, but nodes themselves shouldn't care about what their parents are. There is wisdom in this, but I found that it can complicate the architecture dramatically, so in some instances, this method can be useful to get you out of a pinch.
- I just realised that my method returns null if not found so my test wouldn't have crashed if it didn't work š In any case, give it a crack and you can see it does work.
- The method may be better styled if putting the break condition up top i.e. if parent is null, return default(T). The way I showed just flowed better on video.
š¶ Music tracks from:
- Kayba x Lomme - Explore
- Provided by Lofi Girl
- Watch: https://youtu.be/MozScqdhyIw
- Download/Stream: https://fanlink.to/ExploreEP
You can also visit me at: WEBSITE š https://polysthetic.com THREADLESS š¶ļø https://polysthetic.threadless.com DRIBBBLE š https://dribbble.com/polysthetic YOUTUBE š„ https://youtube.com/c/polysthetic AUDIOMACK š¼ https://audiomack.com/polysthetic ... https://www.youtube.com/watch?v=LWcTQZ-NaXs
58233963 Bytes