Hello! I just had a few questions regarding the cost of GetComponent. I know it’s costly and should mostly be used in awake or start, and cached in a variable. However some times this does not seem practical.
For example, I have an issue currently where i have a waypoint system which works as follows.
- I place out waypoints objects, where each has a waypoint script component. This holds an array to possible other waypoints .
So, when the npc moves to the waypoints, he will get a list of new waypoints he can go to. I currently select one randomly, and I get a quite nice random movement.
However, to get this list of waypoints:
GameObject[ ] allowedWaypoints = nextAndPrevWayPoint[1].GetComponent().allowedWayPoints;
Since “nextAndPrevWayPoint” changes each time I reach the waypoint, I can’t store it, but I use the getcomponent like above.
So, I wonder if this is alright?
The alternative would be to store arrays for all waypoints within the npcControl script, which does not seem like a good idea either.
Any feedback would be welcome 
Kjetil
1 Like
It’s not that costly. If you’re only doing it occasionally, there’s no real difference.
–Eric
ok, so, as long as I don’t do this several times every frame i should be good then. Nice to know
Thanks.
Yep…it’s not like GameObject.Find, since it’s unlikely you’d have more than a few components on any given object.
–Eric
Oh sweet!
i just tested this, it does 5 000 000 getcomponents per second on my pc 2.2ghz corequad in a loop using system time, to get a vector3 from other script.
for comparison, parse int does about 100 000 per second
and if you need to get stuff from many objects, you can use fastparseint (in c its online) name your objects 1-1000 for example, make an array referencing their variable you need to access, and use this code to get the array number frm the object name:
function IntParseFast( value : String) : int
{
var result : int = 0;
for (var i = 0; i < value.Length; i++)
{
var letter : char = value*;*
result = 10 * result + char.GetNumericValue(letter);
}
return result;
}
fastparse does about 15 000 000 equivalent of getcomponent per second. so only 3x faster.
7 Likes