Any GetComponent alternative?

I have projectile that uses GetComponent on hit, which is slow. Any other way to get something from object hit in case there is hundreds of projectiles?

A faster alternative might be to use collision detection.

Here is a lightly altered script (for clarity) from Unity’s documentation:

using UnityEngine;

public class CollisionExample : MonoBehaviour
{
    //Detect collisions between the GameObjects with Colliders attached
    void OnCollisionEnter(Collision other)
    {
        //Check for a match with the specified name on any GameObject that collides with your GameObject
        if (other.gameObject.name == "MyGameObjectName")
        {
            //If the GameObject's name matches the one you suggest, output this message in the console
            Debug.Log("Do something here");
        }

        //Check for a match with the specific tag on any GameObject that collides with your GameObject
        if (other.gameObject.tag == "MyGameObjectTag")
        {
            //If the GameObject has the same tag as specified, output this message in the console
            Debug.Log("Do something else here");
        }
    }
}

Add a collider to the objects colliding, other being the object that was hit.

I highly doubt that GetComponent is your bottle neck here. GetComponent is probably still faster than reading the gameobject’s name unless you have 100 components on the same gameobject. Have you actually used the profiler? GetComponent is implemented in native code and is actually pretty fast. All it has to do is iterate through the list of components on the given object until it finds the one with the type you’re looking for. Since most gameobject have only a couple of components (usually not more than 10) this should be extremely fast.

It’s right that it is recommended to avoid using it every frame when the result can be easily cached. However in the case of a hit there’s no real way around it. Note that reading “gameObject.name” will actually allocate memory for the string because the name is stored on the native side and when you read the name property the name has to be transferred into managed memory. So as a general rule of thumb I would rather call GetComponent than reading the name property.

Note that GetComponent behaves slightly different when testing in the editor compared to when used in an actual build. In case the component you’re looking for does not exist the build game would simply return null. However when testing inside the editor, the editor will actually return a fake null object in order to display a more sophisticated error message. So GetComponent will allocate some garbage memory when testing in the editor but only when the component is not found.