Here are the examples of the csharp api UnityEngine.Component.GetComponents() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
28 Examples
19
Source : LayoutUtilityExtended.cs
with Apache License 2.0
from 365082218
with Apache License 2.0
from 365082218
public static RectOffset GetMargin(RectTransform rect, RectOffset defaultValue)
{
if (rect == null)
return new RectOffset(0, 0, 0, 0);
RectOffset currentMargin = defaultValue;
LayoutElementExtended[] list = rect.GetComponents<LayoutElementExtended>();
for (int i = 0; i < list.Length; i++)
{
LayoutElementExtended layoutElementExtended = list[i];
if (layoutElementExtended.enabled)
{
RectOffset elementMargin = layoutElementExtended.margin;
currentMargin.top += elementMargin.top;
currentMargin.bottom += elementMargin.bottom;
currentMargin.left += elementMargin.left;
currentMargin.right += elementMargin.right;
}
}
return currentMargin;
}
19
Source : UIPopupList.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private void Select(UILabel lbl, bool instant)
{
this.Highlight(lbl, instant);
UIEventListener component = lbl.gameObject.GetComponent<UIEventListener>();
this.selection = (component.parameter as string);
UIButtonSound[] components = base.GetComponents<UIButtonSound>();
int i = 0;
int num = components.Length;
while (i < num)
{
UIButtonSound uibuttonSound = components[i];
if (uibuttonSound.trigger == UIButtonSound.Trigger.OnClick)
{
NGUITools.PlaySound(uibuttonSound.audioClip, uibuttonSound.volume, 1f);
}
i++;
}
}
19
Source : TMP_MaterialManager.cs
with MIT License
from ashishgopalhattimare
with MIT License
from ashishgopalhattimare
public static Material GetMaterialForRendering(MaskableGraphic graphic, Material baseMaterial)
{
if (baseMaterial == null)
return null;
var modifiers = TMP_ListPool<IMaterialModifier>.Get();
graphic.GetComponents(modifiers);
var result = baseMaterial;
for (int i = 0; i < modifiers.Count; i++)
result = modifiers[i].GetModifiedMaterial(result);
TMP_ListPool<IMaterialModifier>.Release(modifiers);
return result;
}
19
Source : AudioSourcesReference.cs
with MIT License
from dag10
with MIT License
from dag10
private void Awake()
{
audioSources = new List<AudioSource>();
foreach (AudioSource audioSource in GetComponents<AudioSource>())
{
audioSources.Add(audioSource);
}
}
19
Source : SteamVR_Camera.cs
with MIT License
from dag10
with MIT License
from dag10
public void ForceLast()
{
if (values != null)
{
// Restore values on new instance
foreach (DictionaryEntry entry in values)
{
var f = entry.Key as FieldInfo;
f.SetValue(this, entry.Value);
}
values = null;
}
else
{
// Make sure it's the last component
var components = GetComponents<Component>();
// But first make sure there aren't any other SteamVR_Cameras on this object.
for (int i = 0; i < components.Length; i++)
{
var c = components[i] as SteamVR_Camera;
if (c != null && c != this)
{
DestroyImmediate(c);
}
}
components = GetComponents<Component>();
if (this != components[components.Length - 1])
{
// Store off values to be restored on new instance
values = new Hashtable();
var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var f in fields)
if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
values[f] = f.GetValue(this);
var go = gameObject;
DestroyImmediate(this);
go.AddComponent<SteamVR_Camera>().ForceLast();
}
}
}
19
Source : TMP_Dropdown.cs
with GNU Lesser General Public License v3.0
from disruptorbeam
with GNU Lesser General Public License v3.0
from disruptorbeam
protected virtual GameObject CreateBlocker(Canvas rootCanvas)
{
// Create blocker GameObject.
GameObject blocker = new GameObject("Blocker");
// Setup blocker RectTransform to cover entire root canvas area.
RectTransform blockerRect = blocker.AddComponent<RectTransform>();
blockerRect.SetParent(rootCanvas.transform, false);
blockerRect.anchorMin = Vector3.zero;
blockerRect.anchorMax = Vector3.one;
blockerRect.sizeDelta = Vector2.zero;
// Make blocker be in separate canvas in same layer as dropdown and in layer just below it.
Canvas blockerCanvas = blocker.AddComponent<Canvas>();
blockerCanvas.overrideSorting = true;
Canvas dropdownCanvas = m_Dropdown.GetComponent<Canvas>();
blockerCanvas.sortingLayerID = dropdownCanvas.sortingLayerID;
blockerCanvas.sortingOrder = dropdownCanvas.sortingOrder - 1;
// Find the Canvas that this dropdown is a part of
Canvas parentCanvas = null;
Transform parentTransform = m_Template.parent;
while (parentTransform != null)
{
parentCanvas = parentTransform.GetComponent<Canvas>();
if (parentCanvas != null)
break;
parentTransform = parentTransform.parent;
}
// If we have a parent canvas, apply the same raycasters as the parent for consistency.
if (parentCanvas != null)
{
Component[] components = parentCanvas.GetComponents<BaseRaycaster>();
for (int i = 0; i < components.Length; i++)
{
Type raycasterType = components[i].GetType();
if (blocker.GetComponent(raycasterType) == null)
{
blocker.AddComponent(raycasterType);
}
}
}
else
{
// Add raycaster since it's needed to block.
GetOrAddComponent<GraphicRaycaster>(blocker);
}
// Add image since it's needed to block, but make it clear.
Image blockerImage = blocker.AddComponent<Image>();
blockerImage.color = Color.clear;
// Add button since it's needed to block, and to close the dropdown when blocking area is clicked.
Button blockerButton = blocker.AddComponent<Button>();
blockerButton.onClick.AddListener(Hide);
return blocker;
}
19
Source : TMP_Dropdown.cs
with GNU Lesser General Public License v3.0
from disruptorbeam
with GNU Lesser General Public License v3.0
from disruptorbeam
private void SetupTemplate()
{
validTemplate = false;
if (!m_Template)
{
Debug.LogError("The dropdown template is not replacedigned. The template needs to be replacedigned and must have a child GameObject with a Toggle component serving as the item.", this);
return;
}
GameObject templateGo = m_Template.gameObject;
templateGo.SetActive(true);
Toggle itemToggle = m_Template.GetComponentInChildren<Toggle>();
validTemplate = true;
if (!itemToggle || itemToggle.transform == template)
{
validTemplate = false;
Debug.LogError("The dropdown template is not valid. The template must have a child GameObject with a Toggle component serving as the item.", template);
}
else if (!(itemToggle.transform.parent is RectTransform))
{
validTemplate = false;
Debug.LogError("The dropdown template is not valid. The child GameObject with a Toggle component (the item) must have a RectTransform on its parent.", template);
}
else if (itemText != null && !itemText.transform.IsChildOf(itemToggle.transform))
{
validTemplate = false;
Debug.LogError("The dropdown template is not valid. The Item Text must be on the item GameObject or children of it.", template);
}
else if (itemImage != null && !itemImage.transform.IsChildOf(itemToggle.transform))
{
validTemplate = false;
Debug.LogError("The dropdown template is not valid. The Item Image must be on the item GameObject or children of it.", template);
}
if (!validTemplate)
{
templateGo.SetActive(false);
return;
}
DropdownItem item = itemToggle.gameObject.AddComponent<DropdownItem>();
item.text = m_ItemText;
item.image = m_ItemImage;
item.toggle = itemToggle;
item.rectTransform = (RectTransform)itemToggle.transform;
// Find the Canvas that this dropdown is a part of
Canvas parentCanvas = null;
Transform parentTransform = m_Template.parent;
while (parentTransform != null)
{
parentCanvas = parentTransform.GetComponent<Canvas>();
if (parentCanvas != null)
break;
parentTransform = parentTransform.parent;
}
Canvas popupCanvas = GetOrAddComponent<Canvas>(templateGo);
popupCanvas.overrideSorting = true;
popupCanvas.sortingOrder = 30000;
// If we have a parent canvas, apply the same raycasters as the parent for consistency.
if (parentCanvas != null)
{
Component[] components = parentCanvas.GetComponents<BaseRaycaster>();
for (int i = 0; i < components.Length; i++)
{
Type raycasterType = components[i].GetType();
if (templateGo.GetComponent(raycasterType) == null)
{
templateGo.AddComponent(raycasterType);
}
}
}
else
{
GetOrAddComponent<GraphicRaycaster>(templateGo);
}
GetOrAddComponent<CanvasGroup>(templateGo);
templateGo.SetActive(false);
validTemplate = true;
}
19
Source : InjectionEntry.cs
with MIT License
from EtiamNullam
with MIT License
from EtiamNullam
private static void EnumerateOtherComponentsOnce(Component component)
{
if (!_firstTimeEnumerate) return;
var comps = component.GetComponents<Component>();
if (comps.Length <= 0) return;
_firstTimeEnumerate = false;
foreach (var comp in comps)
{
State.Logger.Log($"Component (BlockTileRenderer) Name/Type: {comp.name} / {comp.GetType()} ");
}
}
19
Source : MessagesBehavior.cs
with MIT License
from Interactml
with MIT License
from Interactml
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
listeners = animator.GetComponents<IAnimatorListener>();
foreach (MesssageItem ontimeM in onTimeMessage) //Set all the messages Ontime Sent = false when start
{
ontimeM.sent = false;
}
foreach (MesssageItem onEnterM in onEnterMessage)
{
if (onEnterM.Active && onEnterM.message != string.Empty)
{
if (UseSendMessage)
DeliverMessage(onEnterM, animator);
else
foreach (var item in listeners) DeliverListener(onEnterM, item);
}
}
}
19
Source : LevelModuleFelucia.cs
with GNU General Public License v3.0
from Kingo64
with GNU General Public License v3.0
from Kingo64
void Awake() {
var steam = transform.Find("Steam");
particle = steam.GetComponent<ParticleSystem>();
sounds = steam.GetComponents<AudioSource>();
zone = transform.Find("Zone").gameObject;
zone.SetActive(false);
waitTime = Random.Range(5f, 15f);
}
19
Source : ItemBlasterBolt.cs
with GNU General Public License v3.0
from Kingo64
with GNU General Public License v3.0
from Kingo64
void Awake() {
if (GetComponents<StunGlow>().Length > 1) {
Destroy(this);
}
}
19
Source : ItemComlink.cs
with GNU General Public License v3.0
from Kingo64
with GNU General Public License v3.0
from Kingo64
void Awake() {
creature = creature ?? GetComponent<Creature>();
if (!creature) {
Destroy(this);
}
var behaviours = GetComponents<AllyBehaviour>();
foreach (var behaviour in behaviours) {
if (behaviour != this) {
Destroy(behaviour);
}
}
}
19
Source : AutoReferencer.cs
with MIT License
from liangxiegame
with MIT License
from liangxiegame
public static void CalledByEditor(IEnumerable<Object> targets)
{
foreach (Object item in targets)
{
Transform tf = item as Transform;
MonoBehaviour[] monos = tf.GetComponents<MonoBehaviour>();
Undo.RecordObjects(monos, "CalledByEditor");
for (int i = 0; i < monos.Length; i++)
{
//找脚本上的CalledByEditor函数,编辑器调用
MethodInfo methodInfo = monos[i].GetType()
.GetMethod("CalledByEditor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo == null)
{
continue;
}
Debug.Log(monos[i].name + " Method CalledByEditor Invoke");
methodInfo.Invoke(monos[i], null);
}
}
}
19
Source : AutoReferencer.cs
with MIT License
from liangxiegame
with MIT License
from liangxiegame
public static void FindReferences(IEnumerable<Object> targets)
{
foreach (Object item in targets)
{
Transform tf = item as Transform;
MonoBehaviour[] monos = tf.GetComponents<MonoBehaviour>();
Undo.RecordObjects(monos, "FindReferences");
for (int i = 0; i < monos.Length; i++)
{
//按照变量名自动找引用
FindReferences(monos[i]);
}
}
}
19
Source : CarAudio.cs
with GNU General Public License v2.0
from marssociety
with GNU General Public License v2.0
from marssociety
private void StopSound()
{
//Destroy all audio sources on this object:
foreach (var source in GetComponents<AudioSource>())
{
Destroy(source);
}
m_StartedSound = false;
}
19
Source : PlayerHealth.cs
with GNU General Public License v3.0
from MinhDin
with GNU General Public License v3.0
from MinhDin
void OnCollisionEnter2D (Collision2D col)
{
// If the colliding gameobject is an Enemy...
if(col.gameObject.tag == "Enemy")
{
// ... and if the time exceeds the time of the last hit plus the time between hits...
if (Time.time > lastHitTime + repeatDamagePeriod)
{
// ... and if the player still has health...
if(health > 0f)
{
// ... take damage and reset the lastHitTime.
TakeDamage(col.transform);
lastHitTime = Time.time;
}
// If the player doesn't have health, do some stuff, let him fall into the river to reload the level.
else
{
// Find all of the colliders on the gameobject and set them all to be triggers.
Collider2D[] cols = GetComponents<Collider2D>();
foreach(Collider2D c in cols)
{
c.isTrigger = true;
}
// Move all sprite parts of the player to the front
SpriteRenderer[] spr = GetComponentsInChildren<SpriteRenderer>();
foreach(SpriteRenderer s in spr)
{
s.sortingLayerName = "UI";
}
// ... disable user Player Control script
GetComponent<PlayerControl>().enabled = false;
// ... disable the Gun script to stop a dead guy shooting a nonexistant bazooka
GetComponentInChildren<Gun>().enabled = false;
// ... Trigger the 'Die' animation state
anim.SetTrigger("Die");
}
}
}
}
19
Source : Enemy.cs
with GNU General Public License v3.0
from MinhDin
with GNU General Public License v3.0
from MinhDin
void Death()
{
// Find all of the sprite renderers on this object and it's children.
SpriteRenderer[] otherRenderers = GetComponentsInChildren<SpriteRenderer>();
// Disable all of them sprite renderers.
foreach(SpriteRenderer s in otherRenderers)
{
s.enabled = false;
}
// Re-enable the main sprite renderer and set it's sprite to the deadEnemy sprite.
ren.enabled = true;
ren.sprite = deadEnemy;
// Increase the score by 100 points
score.score += 100;
// Set dead to true.
dead = true;
// Allow the enemy to rotate and spin it by adding a torque.
GetComponent<Rigidbody2D>().AddTorque(Random.Range(deathSpinMin,deathSpinMax));
// Find all of the colliders on the gameobject and set them all to be triggers.
Collider2D[] cols = GetComponents<Collider2D>();
foreach(Collider2D c in cols)
{
c.isTrigger = true;
}
// Play a random audioclip from the deathClips array.
int i = Random.Range(0, deathClips.Length);
AudioSource.PlayClipAtPoint(deathClips[i], transform.position);
// Create a vector that is just above the enemy.
Vector3 scorePos;
scorePos = transform.position;
scorePos.y += 1.5f;
// Instantiate the 100 points prefab at this point.
Instantiate(hundredPointsUI, scorePos, Quaternion.idenreplacedy);
}
19
Source : Mechanism.cs
with Apache License 2.0
from mogoson
with Apache License 2.0
from mogoson
public virtual void Initialize()
{
if (IsInitialized)
{
return;
}
limiters.AddRange(GetComponents<ILimiter>());
IsInitialized = true;
}
19
Source : NetworkTranformChild.cs
with MIT License
from NicolasPCouts
with MIT License
from NicolasPCouts
void OnValidate()
{
// root parent of target must have a NetworkTransform
if (m_Target != null)
{
Transform parent = m_Target.parent;
if (parent == null)
{
if (LogFilter.logError) { Debug.LogError("NetworkTransformChild target cannot be the root transform."); }
m_Target = null;
return;
}
while (parent.parent != null)
{
parent = parent.parent;
}
m_Root = parent.gameObject.GetComponent<NetworkTransform>();
if (m_Root == null)
{
if (LogFilter.logError) { Debug.LogError("NetworkTransformChild root must have NetworkTransform"); }
m_Target = null;
return;
}
}
if (m_Root != null)
{
// childIndex is the index within all the NetworkChildTransforms on the root
m_ChildIndex = UInt32.MaxValue;
var childTransforms = m_Root.GetComponents<NetworkTransformChild>();
for (uint i = 0; i < childTransforms.Length; i++)
{
if (childTransforms[i] == this)
{
m_ChildIndex = i;
break;
}
}
if (m_ChildIndex == UInt32.MaxValue)
{
if (LogFilter.logError) { Debug.LogError("NetworkTransformChild component must be a child in the same hierarchy"); }
m_Target = null;
}
}
if (m_SendInterval < 0)
{
m_SendInterval = 0;
}
if (m_SyncRotationAxis < NetworkTransform.AxisSyncMode.None || m_SyncRotationAxis > NetworkTransform.AxisSyncMode.AxisXYZ)
{
m_SyncRotationAxis = NetworkTransform.AxisSyncMode.None;
}
if (movementThreshold < 0)
{
movementThreshold = 0.00f;
}
if (interpolateRotation < 0)
{
interpolateRotation = 0.01f;
}
if (interpolateRotation > 1.0f)
{
interpolateRotation = 1.0f;
}
if (interpolateMovement < 0)
{
interpolateMovement = 0.01f;
}
if (interpolateMovement > 1.0f)
{
interpolateMovement = 1.0f;
}
}
19
Source : RectTransformExtensions.cs
with MIT License
from silphid
with MIT License
from silphid
public static IEnumerable<T> OfComponentImplementing<T>(this IEnumerable<RectTransform> This)
{
return This.SelectMany(g => g.GetComponents<T>());
}
19
Source : ScrollRectEx.cs
with MIT License
from silphid
with MIT License
from silphid
private void DoForParents<T>(Action<T> action) where T : IEventSystemHandler
{
var parent = transform.parent;
while (parent != null)
{
foreach (var component in parent.GetComponents<Component>().OfType<T>())
action(component);
parent = parent.parent;
}
}
19
Source : QuickBase.cs
with MIT License
from XINCGer
with MIT License
from XINCGer
public void DisabledQuickComponent(string quickActionName){
QuickBase[] quickBases = GetComponents<QuickBase>();
foreach( QuickBase qb in quickBases){
if (qb.quickActionName == quickActionName){
qb.enabled = false;
}
}
}
19
Source : QuickBase.cs
with MIT License
from XINCGer
with MIT License
from XINCGer
public void EnabledQuickComponent(string quickActionName){
QuickBase[] quickBases = GetComponents<QuickBase>();
foreach( QuickBase qb in quickBases){
if (qb.quickActionName == quickActionName){
qb.enabled = true;
}
}
}
19
Source : UnityEngine_ComponentWrap.cs
with MIT License
from XINCGer
with MIT License
from XINCGer
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetComponents(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2)
{
UnityEngine.Component obj = (UnityEngine.Component)ToLua.CheckObject<UnityEngine.Component>(L, 1);
System.Type arg0 = ToLua.CheckMonoType(L, 2);
UnityEngine.Component[] o = obj.GetComponents(arg0);
ToLua.Push(L, o);
return 1;
}
else if (count == 3)
{
UnityEngine.Component obj = (UnityEngine.Component)ToLua.CheckObject<UnityEngine.Component>(L, 1);
System.Type arg0 = ToLua.CheckMonoType(L, 2);
System.Collections.Generic.List<UnityEngine.Component> arg1 = (System.Collections.Generic.List<UnityEngine.Component>)ToLua.CheckObject(L, 3, typeof(System.Collections.Generic.List<UnityEngine.Component>));
obj.GetComponents(arg0, arg1);
return 0;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Component.GetComponents");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
19
Source : ComponentExtensions.cs
with MIT License
from zios
with MIT License
from zios
public static void MoveUp(this Component current){
if(current.IsNull()){return;}
Component[] components = current.GetComponents<Component>();
int position = components.IndexOf(current);
int amount = 1;
if(position != 0){
while(components[position-1].hideFlags.Contains(HideFlags.HideInInspector)){
position -= 1;
amount += 1;
}
}
current.Move(-amount);
}
19
Source : ComponentExtensions.cs
with MIT License
from zios
with MIT License
from zios
public static void MoveDown(this Component current){
if(current.IsNull()){return;}
Component[] components = current.GetComponents<Component>();
int position = components.IndexOf(current);
int amount = 1;
if(position < components.Length-1){
while(components[position+1].hideFlags.Contains(HideFlags.HideInInspector)){
position += 1;
amount += 1;
}
}
current.Move(amount);
}
19
Source : ComponentExtensions.cs
with MIT License
from zios
with MIT License
from zios
public static void MoveToTop(this Component current){
if(current.IsNull()){return;}
Utility.DisconnectPrefabInstance(current);
Component[] components = current.GetComponents<Component>();
int position = components.IndexOf(current);
current.Move(-position);
}
19
Source : ComponentExtensions.cs
with MIT License
from zios
with MIT License
from zios
public static void MoveToBottom(this Component current){
if(current.IsNull()){return;}
Utility.DisconnectPrefabInstance(current);
Component[] components = current.GetComponents<Component>();
int position = components.IndexOf(current);
current.Move(components.Length-position);
}