- Home /
How to GetComponent that derived from a certain base class?
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.
Answer by Landern · Aug 15, 2016 at 09:20 PM
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
What if there are many components derived from Collider attached on the game object? What will be returned by GetComponent() ?
Answer by ScaniX · Aug 15, 2016 at 09:17 PM
GetComponent<Collider>() != null
What if there are many components derived from Collider attached on the game object? What will be returned by GetComponent() ?
Well, the first. You can use GetComponents<Collider>()
to get an array of all of them. :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612090849im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Parent class in getcomponent 1 Answer
How can I access an inherited method from a separate (collided) object? 1 Answer
NullReferenceException: Object reference not set to an instance of an object ..... 1 Answer
Having trouble understanding parenting with componants 0 Answers