- Home /
using GameObject.Find and Cpu usage
So for the most part ive been using GameObject.Find for my audio masters, long story short im finding an object and referencing a specific script attached to that object, however ive heard that GameObject.Find consumes a lot of cpu and its much better to find with tags which i have been doing for the most part
Anyways, for this problem i need to use find for reasons that would take to long to explain but ive found a workaround and i think it might be less consuming on the cps, let me know
private GameObject spikesound;
void Start () {
GameObject AudioObj = GameObject.FindWithTag("AudioMaster");
spikesound = AudioObj.transform.Find ("TimedSpikeAudio").gameObject;
will this be less consuming of my cpu? thought id querry it with you before i delved into changing everything
Answer by Baste · Sep 01, 2015 at 04:14 PM
The reason for why it's expensive to use Find is that Unity has to look through all of the objects and check their name. The looking part is the bad one.
Tags are a bit better - there are only 32 possible tags, so (I assume) there are some dictionary-like structures that maps from tags to objects, which would make it a lot faster to search.
So, since you're only doing this in Start, the cost of the FindWithTag and Find operations only happens once, so this should not be a problem. Unless that Start method is called a lot - like if this is on a prefab that you create many copies of.
Still, directly referencing the object is faster. Why not just have the spikesound object as a public variable, and assign it in the inspector? If you're creating these objects at runtime, that's not possible, but otherwise it's often the easiest to work with, and the fastest.
What script is this code on? Do you have any script on the spikesound object? Both of those will help me give you better answers.
There's no limit on the number tags that I know of. You're thinking of layers, but those are just 32-bit numbers.
Thought i replied a dew days back but guess it didnt send :p
this script in particular is referenced in most of my game mechanics (such as spikes moving up and down in this case) which play sound through an audio master to stop them overlapping, the main reason im querying about this is because i may have hundereds of these spike mechanics in my level, and each one of them has to find the audio master for it, now they all do this in start but someone mentioned i might get a few secconds of stuttering if i just use gameobject.find, i thought the method i posted, which finds with tag first might help aleviate that
hope to hear back soon and thanks for your help