For example, I want to check whether an object contains Collider component or not. It does not matter for any type of Collider, whether it’s 2D, 3D , Box, Sphere or Polygon. If there is one, the function should yield TRUE as a result.
GetComponent() != null
All specific colliders derive from collider, this includes BoxCollider, SphereCollider, etc.
So you can use the base class all colliders have in common:
GetComponent<Collider>(); // c#
GetComponent.<Collider>(); // javascript/unityscript
To test this i setup three 3d GameObjects in the scene, each i attached a collider component that corresponded to it’s 3d primitive sharp(cube gets box collider, etc).
I made a script that got all objects in the scene that are GameObjects. This returned the three objects i created and two that are standard to most scenes(the light and the camera). I debugged into the update method to watch if a collider is found.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Colliders : MonoBehaviour {
List<GameObject> gos = new List<GameObject>();
// Use this for initialization
void Start () {
gos = GameObject.FindObjectsOfType<GameObject>().ToList();
}
// Update is called once per frame
void Update () {
foreach(GameObject go in gos)
{
bool isCollider = go.GetComponent<Collider>() == null ? false : true;
}
}
}
This code only shows that using the derived type that derived from Component( like all the colliders do) will return using GetComponent. Obviously things that don’t derive from Component will not be returned, even MonoBehaviour is a Component, MonoBehaviour->Behaviour->Component->etc