Calling Another Script Does It Hurt?

Hello

If I remember correctly I was told that it’s not a good idea to call another script from a script. By using GetComponent (). As it is taxing on memory or something like that. Anyone know if this is the case?

If it is, is there a less taxing way or better way to interact with a script. Or should I just try to call another script as little as possible?

If you can store the component reference in a variable and reuse the variable, always do that.

Generally you will do it in Awake or Start and store the component in a variable for use in the rest of the class.

Just don’t call it more than you need to (like every frame in Update), and it will be fine.

3 Likes

Thank you, you’ve been most helpful.

1 Like

This isn’t the first time this has been asked on these forums, and from experience this gets twisted into “don’t use getcomponent in update” which isn’t correct. The emphasis is on “more than you need to”.

If you are working in the Update function and working with dynamic references (for example the raycasthit from a raycast which can change from one frame to the next) and you want a component based on that reference’s current state it’s perfectly correct to use getcomponent.

If you are working in the Update function and you are using a reference that isn’t going to change (for example the rigidbody attached to this gameobject, which is never removed) you should do the getcomponent in start/awake and use the reference in the update function rather than getting the component every frame in update function.

4 Likes

Thank you for the information! You’ve been very helpful!