Helper functions I can't live without in Unity
Today I share with you some of my beloved helper functions. I use these in every Unity project and I'm sure they'll help you out, too!
❤️ Become a Tarobro on Patreon: / tarodev
=========
🔔 SUBSCRIBE: bit.ly/3eqG1Z6
🗨️ DISCORD: / discord
✅ MORE TUTORIALS: / tarodev
About Tarodev:
Develop video games like a pro!
Whether you're a beginner or a seasoned game developer, you'll find lots of useful tips and tricks to boost your development career. Visit the channel: / @tarodev
0:00 Intro
0:27 Camera Reference
1:05 None-allocating WaitForSeconds
2:03 Is the pointer over UI?
3:30 Find world point of canvas element
4:51 Quickly destroy all child objects
5:36 Outro
Пікірлер: 88
Camera.main is not necessary expensive anymore, but I still use this helper method as it's easy access.
@technofeeliak
Жыл бұрын
Tell me it's expensive, making an entire video on how to reduce the processing load and then write a comment under the video telling everyone this may be completely unnecessary.
@mrpancakeguy
Жыл бұрын
@@technofeeliak I've seen some of your video's.
@jackalcz2806
Жыл бұрын
@@technofeeliak Yep, he talking about camera main doing this. I immediately opened up my project and created script, cause i didnt know it is doing this crap like iterating thru all objects, then i have read this comment and i immediately deleted the script and closed the project. lol :D
@TheSyberglitch
Жыл бұрын
Just wondering how the Camera helper function (for Camera.main) works for you in projects with multiple scenes.
The WaitForSeconds dictionnary is brilliant! I knew about the garbage and cached them inside my scripts but this is so much simpler.
That 'isOverUI' bool is quite an awesome tool to have. Thanks for the tutorial!
@Tarodev
2 жыл бұрын
There is actually a unity supplied one: docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html I didn't know at the time :)
This is great, good to know I was on the right track when I started my own "library functions". I'm loving these short n sweet videos.
Mate, I've been grinding games for the past 6 years and falling in love with your channel!!! So much good stuff here!!!
I am quite new to Unity but I like your videos and also for newbies most of the time easy to understand. Thanks! (Subscribed of course!)
I would watch 1 million videos just like this, please make more
Legend ! Thanks very much !! :D I am learning a lot from your videos. Liked and Subscribed.
That OverUI is what I've been trying to solve for 6 months Thanks man
That was great. Very helpful and appreciated.
There isnt videos like yours, u help me alot, never stop doing it haha... I tried the find world point of canvas element and i couldnt make it work on 2d projects neither in 3d.. the objects follow the element but they were small (i couldnt ser it) it almost worked with the camera on screenspace camera but only at x0y0 position, when i move the text the cube moved really fast out of camera (while the text was still inside)
Wow! That's definitely a video I'll add to my bookmarks :)
@Tarodev
3 жыл бұрын
Glad you found something useful ❤️
Awesome video, i really need more of this helpers)
4:15 oh my days, thank you... I've been working around this for so long, mainly by having a camera that renders to a render texture, and then using that as a UI element🤦♂
Thank you sir!
awesome ! thank you for sharing
@Tarodev
3 жыл бұрын
Hope some of them help you out :)
The ones I usually want are a few specialized math function, such as one called "ModRight()," along with list extension for random selections and random shuffling. For a camera, I usually just drag it on to a relevant game object.
Hey dude... Good video but at 1:36 you never unblur the helper version of the coroutine.... I cant see how you call the waitforseconds....
@jonathangantt7520
2 жыл бұрын
Just watching this, it looks like the following: IEnumerator Good() { for(var i = 0; i yield return Helpers.GetWait(0.01f); } }
FYI for anyone concerned: The == operator is overridden by Unity, so it checks if the object has been destroyed, otherwise the Camera helper would be a memory leak when switching scenes.
@edukee
2 жыл бұрын
yeah my first thought was "oh this is going to be a disaster once the scene is changed", so what you're saying all these years I didn't have to write all that extra safety code to avoid leakage?
@MaxIzrin
2 жыл бұрын
@@edukee Unfortunately... yes. This has been implemented pretty much from the start. Though not many people seem to be aware of it, until they encounter some bug as a result of this behavior. If you want to check if a variable is actually null, you have to use the "is" keyword. That cannot be overridden. if ( component is null ) { }
I have several helper methods for different scenarios where I need to access a random child of a transform or a random value in an array or a list. Just so that I don't have to write Random.Range again and again.
Hi, for the camera thing you can also do in a single line: public static Camera Camera => _camera ??= Camera.main; *Unity 2020.2 or higher. Thanks for your great videos and tips ;)
@Tarodev
2 жыл бұрын
That's beautiful.
@vertxxyz
2 жыл бұрын
You should avoid using modern null checking operators with Unity objects because Unity Objects evaluate to null without actually being null, and that behaviour is only overridden for equality. Null conditional (?.) and the null coalescing (??, ??=) operators could not be overridden by Unity. They will only work correctly when references are explicitly null, so if you changed scenes (destroying the old main camera) this would fail.
@Tarodev
2 жыл бұрын
@@vertxxyz I really dislike the operator override for null... I really confuses new devs (at least on my discord).
@RealisiticEdgeMod
2 жыл бұрын
1:06 Did you mean to say cache? You said kaysche.
@newarteest
2 жыл бұрын
@@RealisiticEdgeMod I worked with a British developer who also pronounced it that way. I think it may be pronounced differently in England and Australia?
Whoever doesn't follow you misses a big chunk of hands on experience.
Here is my tips : F2 = u can rename objects fast. If u turn on the playmode u can stop then click on maximize on play then click again on play (To disable/enable fullscreen). Instead of Debug.Log() I sometimes use print().
@KaiDevvy
2 жыл бұрын
You can also do shift + space to fullscreen whatever window (including the game window, even while in play mode) your mouse is hovering over. Shift + space again exits fullscreen. I don't recommend using print(), as it's exclusive only to MonoBehaviour and is just a wrapper for Debug.Log. If you decided you didn't want to use MonoBehaviour for your class anymore, you'd have to go through and change every call to print().
I'm surprised to see float as keys to a dictionary as 0.01f is not always equal to 0.01f due to floating point precision issues. For camera I did the same but instead of static it's a system loaded in the current scene. Good tips overall. Thanks for taking the time to share!
@firebiscuitgaming7624
2 жыл бұрын
side note: instead of having a kitchen sink Helpers class you can have extenstion methods in a class dedicated to the subject for example TransformHelpers with your destroyChildren.
@Tarodev
2 жыл бұрын
The float is fine here as it's human interaction. We're the ones putting in the wait times. I certainly wouldn't recommend it otherwise, but it's never failed me yet.
@firebiscuitgaming7624
2 жыл бұрын
I suspect you get lucky here because the compiler will extract all those constants, probably in a single constant for all 0.1f that you write.
@RubenPita
2 жыл бұрын
You only get precision errors from calculations. Yeah the compiler might do some magic for that but it doesn't matter since you're writing float constants.
I usually makes mine into a singleton and call it as "Reference Manager"
I just wonder if putting game elements inside a static class may create issues in GC, as static classes never disposed and collected by GC and so the objects which static classes holds? So your scenes memory may not be released even you unload the scene?
The (unity)Object.Destroy was new for me. I think I have done this with instantiate. Is this considered good practice?
@Tarodev
2 жыл бұрын
Perfectly fine. You'll find monobehaviours 'Destroy' Method is just a wrapper for Object.Destroy
I am quite new with unity, around 3.45, I do not quite understand how the Cube script call method from the Helper script? something to do with "static" in Helper script? (Most of the time I have to declare gameObject then drag&drop empty object with the script I want to call attached)
Hey, just curious with the 'return' and its functionality as it always confuses me. For example in 2:54 you return result > 0 and I'm just curious what the return actually does.
@Tarodev
2 жыл бұрын
Okay so in this case, we are returning the result of 'result > 0', which is a boolean. You could separate this into 2 lines, but this is cleaner 😊
@HassaanALal
2 жыл бұрын
in simple words for noobs like me, it does this: if (result > 0) return true; else return false; (which is very dumb once you know the new trick)
I always wanted to create my Helper script .. but the problem is public static class doesn't work on some devices for some reason .. and sometimes they get garbage collected if you don't frequently use them .. looked for a solution for sometimes but nothing is helping
where did you learn to hardcode your own game? I really wish i could be more flexible like this
@Tarodev
2 жыл бұрын
Lots of practice mate, just keep learning and coding.
good vid subscribes. I am a beginner in unity by rhe way.
@Tarodev
3 жыл бұрын
You're at the beginning of a wonderful journey 😊 good luck!
Poor ice cream D:
How do we use the Wait dictionary? you didn't unblur the good example
@Tarodev
2 жыл бұрын
My bad 🙏 var wait = Helpers.GetWait(69);
So, it's not a problem if multiple coroutines are sharing a single instance of a WaitForSeconds? They don't all end-up synchronized?
@tonychristney2728
Жыл бұрын
No, if you look into the IL for a WaitForSeconds instance, all it has is the wait duration field. How long the coroutine has waited is tracked internally by the C++ engine.
make a series about the basics of c# and unity.
@Tarodev
3 жыл бұрын
You read my mind ;)
@noobcraft5712
3 жыл бұрын
@@Tarodev ohhhh good :)
I'm new to c# and Unity and try to understand what's going on in the last method "DeleteChildren()" 1.) If I understand correctly, "this" extends the transform component with a "DeleteChildren" method. 2.) I'm confused why and since when the transform component have children (why not use gameObject instead?) 3.) This method isn't called recursive, so how can it also delete sub children? (you mentioned a complete level clean up with giving the parent object) Unfortunately I'm not a native english speaker and perhaps I misunderstand this concept...
@Tarodev
2 жыл бұрын
1. The 'this' keyword is used in extention methods to allow the method to be chained directly from the object. For example transform.MyNewFunction. We have added a function to the transform type. 2. We take in transform as that's what we use to iterate children. We can't do it directly from the game object. But it's personal preference if you'd like to take in a game object. 3. I'm sure after I say this you'll think it's super obvious, but if you destroy a game object it also destroys all its children, so no need for recursion.
@jugibur2117
2 жыл бұрын
@@Tarodev Thanks for your explainations (and all the good stuff!) PS: Meanwhile I have read that every component has a link to it's gameObject, so I understand that construction.
@Tarodev
2 жыл бұрын
@@jugibur2117 Yup! I see what you're saying though... It makes sense that a function which destroys gameObjects should take in a gameObject. Totally up to you if you'd prefer it that way and just do gameObject.transform for the loop :)
I was told that in 2019 unity has auto cache the main camera for you. Do you know if this is true?
@abdrnasr
2 жыл бұрын
You can cache it on your own and avoid any kind of uncertainty. It won't cost much just the reference of the camera.
Could you maybe make a Pastebin of this script?
You have another video where you claim Coroutines are bad and async is superior, here you talk about wait for seconds for coroutines - so, ur using them anyway? Why, how, when?
post the code my man
@Tarodev
Жыл бұрын
This video is so old 😭 it's long gone, sorry bud
@JayadevHaddadi
Жыл бұрын
@@Tarodev hehe i know it is just a few lines of code but lazy programmers like myself just like to copy paste anyway i love the idea. i have my own global static methods and extension methods globally in each project, always nice to be able to add a few new ones there:) mostly i use extension functions to give lists kind of class functionality :)
Good job! But I use Godot Game engine though..
Cant we use just 'EventSystem.current.IsPointerOverGameObject()' instead of 'IsOverUi()' method? Btw I learned much from your videos. Thanks a lot!
This code can instantly give you an error if you forgot to add a component to an object instead of getting null, yes you can use TryGetComponent(), but it's not always appropriate. public static T GetComp(this GameObject gameObject) where T : Component { T comp = gameObject.GetComponent(); Assert.IsNotNull(comp, $"Missing {typeof(T).FullName} component of {gameObject.name} game object or it child!"); return comp; }
For the IsOverUI, this seems to be working, with less allocations: private static PointerEventData _eventDataCurrentPosition = new PointerEventData(EventSystem.current); private static List _raycastResults = new List(); public static bool IsOverUI() { _eventDataCurrentPosition.position = Input.mousePosition; EventSystem.current.RaycastAll(_eventDataCurrentPosition, _raycastResults); return _raycastResults.Count > 0; } Am I right ?
@Tarodev
2 жыл бұрын
I've since found this: docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.html
@alexxkrehmen772
2 жыл бұрын
@@Tarodev This link is pointing to quite a lot of stuff, which one are you talking about exactly ? ;)
@Tarodev
2 жыл бұрын
@@alexxkrehmen772 I'm a goose. Wrong link. Here: docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
@alexxkrehmen772
Жыл бұрын
@@Tarodev Thanks ! 😁