- Home /
OnMouseOver or Use a Raycast?
I am just wondering what would be more efficient. Adding a script to an object with a OnMouseOver function that access a static variable, or using a raycast system with GetComponent? This is for a targeting system for my game. Static variable can be used in this instance.
Thanks: James
Don't use Static variables unless you're accessing something like a control script that appears in every scene.
Really you could get either to work without using statics, do you want to elaborate on what you're trying?
Answer by LaireonGames · Feb 22, 2015 at 08:19 PM
Golden question, does it matter? The one thing I have been taught and stand by as a golden rule to development, if its not broke, don't fix it.
I use a combination of both systems over a few projects and never noticed a problem with either. My gut would say that OnMouseOver will be a tad more optimised since its hooked to the engine and can benefit from performance gains on the C++ side but honestly its probably minute.
Just go with whichever system you are more comfortable/familiar with and don't worry about micro-optimisations unless there is a problem.
Though as an FYI GetComponent will always be a bit slow, nothing major but I avoid it as a rule and pass references where possible instead.
@$$anonymous$$2Games: "nothing major but I avoid it as a rule and pass references where possible ins$$anonymous$$d."
how does this "pass references" thing work? I'm only aware of GetComponent. How does your method work? I am interested in learning new ways to do things that are supposedly faster. Like how woudl you type the code to "pass reference"?
Its not strictly true but basically every variable of a class or object is passed as a reference in C#
So basically:
class Example : $$anonymous$$onoBehaviour
{
public Animation animation;
public Enemy enemy;//these are basically passing reference. By making them public you can assign the values in the editor
void Update()
{
enemy.Hurt();
animation.Play();//this way you are speaking to the class directly
GetComponent<Animation>().Play();//whereas this way Unity has to search for the animation component each time this is called. To be fair for what it does it is very optimised but it will always be slower than using the reference directly
}
}
Even calling gameObject or transform is just a quick way of typing getComponent() so if you are really looking for frames these can be stored as well.
Thank You so much for an honest answer without going all technical and talking about problems that are totally irrelevant. Im going with the static variable due to it not being a problem for this project. Thank you agian, James.