- Home /
Are singletons in C# faster than SendMessage/GetComponent?
I've read some things on Answers about SendMessage being relatively slow... But recently I found out a cool way to communicate between scripts using singetons, for example:
static public scriptName Instance;
public int doSomething{
set{
code goes here
}
}
I can call this from any script!
I'm making a mobile game right now so performance is important to me
Answer by iwaldrop · May 14, 2013 at 03:54 PM
Yes, using a singleton or an event will be much faster than using SendMessage or GetComponent. The reason is that both of the latter options traverse every component in the gameobject in order to find either a method to call (via reflection which is slower than making a method call), or to find he component desired. Two things you can do to avoid this is to, as you suggested, use a singleton, or cache a reference to the component, as such:
SomeComponent cachedComponent = GetComponent< SomeComponent >();
Then you can call a method on that component via:
cachedComponent.SomePublicMethod();
You can also look into an event model to allow several classes to respond to an event that occurs. Please search google for 'c# events' for more information. In closing, avoid send message. It's not only slow, but it's difficult to follow a code path because it will call a message who h matches a string name on the game object you call it on. There is no way to know which component that method is on, and when others look at your code it's like a dead end without some manual hunting.
Thanks for your reply!
btw found this: Events, Delegates & Singletons
imo caching references of components is way cleaner than using the singleton pattern.
but the downside is that if you create a new script, you'll have to create new variables n stuff
@skoandi The downside with singleton is that you become dependent upon static data which often makes debugging issues far harder. Take a read through the following Q&A: http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Script Efficiency 1 Answer
Low Priority Methods In LateUpdate? 1 Answer
byte[] to Texture kills performance 3 Answers