- Home /
Calling function found on hundreds objects(best way?)
Hi. I ve been building a script that every 0.1 seconds calls a function on around 250 objects. Game runs fine, but I see 250 cpu calls on the script, so I am wondering if thats fine.
The "main" script looks like this;
GameObject[] lods;
float dist;
Transform player;
MeshRenderer[] renders;
int update_time;
// Use this for initialization
void Start ()
{
lods = GameObject.FindGameObjectsWithTag("as_lod");
print( lods.Length );
InvokeRepeating("lod_Check", 0, 0.1F);
}
// Update is called once per frame
void lod_Check ()
{
foreach( GameObject ob in lods )
{
ob.SendMessage("render_check");
}
}
Is there a better way to call functions on multiple objects or is this fine? The other objects have to do a vec3 distance check ,each time they get called.
Thanks for your time.
Answer by Pharan · Oct 06, 2015 at 01:46 PM
There are many faster ways to do this than SendMessage. Note this old topic: http://answers.unity3d.com/questions/262087/sendmessage-slows-down-unity-dramatically.html
Not to say that SendMessage isn't handy for when you're still starting to implement things. But when it's time to clean up and optimize (or it was already slowing down to begin with), SendMessage should be one of the first things to go.
There was a Unity Tips video about this a while back with Tim Cooper as the speaker: https://www.youtube.com/watch?v=Ozc_hXzp_KU
He recommends that all your instances register to a centralized/singleton script by passing itself (this) to it. It would probably then add it to a List or array. Then just foreach that array.
You already have the lods GameObject array so you probably don't need the self-registry system. Just store a List and find all those components at load time using GetComponent and adding it to the List. Then foreach the List, calling render_check().
btw, you're using unusual naming for your method names. The standard for C# methods is PascalCase. Are you new to Unity?
Ok,so the main bad thing would be Send$$anonymous$$essage. I am not new to Unity, I just made up that script quickly to test out things, and I dont care that much about na$$anonymous$$g as long as the script works.
There are also some potential issues with foreach generating garbage due to a bug in the old version of $$anonymous$$ono Unity is using, as well as some other cases. You may be better off iterating using a for loop or manually getting the enumerator.
Ok, I ve changed the script a bit.
LODHedge[] Lod_Script;
// Use this for initialization
void Start ()
{
Lod_Script = FindObjectsOfType<LODHedge>();
InvokeRepeating("UpdateOthers", 0, 0.1F);
}
// Update is called once per frame
void UpdateOthers ()
{
foreach ( LODHedge script in Lod_Script )
{
script.render_check();
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
space wrap 3D 1 Answer
WorldToScreenPoint in Update/OnGUI: Bad Performance 1 Answer