Confused on targeting

I don’t understand how we know that the object we’re triggering is of type target because the object is just a sphere with a collider.

public List<Target> targets = new List<Target>();

    private void OnTriggerEnter(Collider other)
    {
        if (!other.TryGetComponent<Target>(out Target target)){return;}
        
        targets.Add(target);
        
        
    }

    private void OnTriggerExit(Collider other)
    {
        if (!other.TryGetComponent<Target>(out Target target)){return;}
        
        targets.Remove(target);
    }

On the first line of OnTriggerEnter and OnTriggerExit we try to get the Target component. If the sphere with a collider does not contain that component, it is not a target and we leave the function. If we don’t leave the function, we know that it’s a target.

You’ll see at the bottom of the inspector image that you shared, there is a Target component. That is what makes the sphere with a collider also a target

2 Likes

Ohhh so the Target component is the Target script?

Yes, that is exactly what it is. Any MonoBehaviour you create is a component

ok thanks :+1:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms