using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MyFrameworkPure
{
///
/// 游戏物体扩展类
///
public static class GameObjectExtension
{
///
/// 判断鼠标是否在游戏物体上
///
///
///
///
public static bool IsOnMouse(this GameObject go, Camera camera)
{
if (!camera)
{
Debug.LogError("没有合适的相机!");
return false;
}
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hitInfo))
{
if (hitInfo.transform.gameObject.Equals(go) || hitInfo.transform.IsChildOf(go.transform))
return true;
}
return false;
}
///
/// 判断是否点击到物体
///
///
///
///
public static bool IsOnMouseDown(this GameObject go, Camera camera)
{
return Input.GetMouseButton(0) && go.IsOnMouse(camera);
}
///
/// 获取物体的碰撞边界
///
///
///
public static Bounds GetBounds(this GameObject go)
{
Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
MeshRenderer[] renderers = go.GetComponentsInChildren();
renderers.ForEach((x) =>
{
if (bounds.size == Vector3.zero)
{
bounds = x.bounds;
}
bounds.Encapsulate(x.bounds);
});
return bounds;
}
///
/// 获取或添加组件
///
///
///
///
public static T GetOrAddCompoent(this GameObject go) where T : Component
{
T t = go.GetComponent();
if (!t)
t = go.AddComponent();
return t;
}
public static T[] GetComnponentsInChildrenWithoutSelf(this GameObject go) where T : Component
{
T[] components = go.GetComponentsInChildren();
return components.Except(go.GetComponents()).ToArray();
}
public static T GetBaseComponentInParent(this GameObject go) where T:Component
{
T[] components = go.GetComponentsInParent();
return components.FirstOrDefault(x => x.GetType() == typeof(T));
}
///
/// 获取子物体的所有材质(包括自身)
///
///
///
///
///
public static Material[] GetMaterialsInChildren(this GameObject go, bool includeInactive = false, Predicate predicate = null)
{
List matlist = new List();
MeshRenderer[] renderers = go.GetComponentsInChildren(includeInactive);
renderers.ForEach(x =>
{
Material[] mats = Application.isPlaying ? x.materials : x.sharedMaterials;
mats.ForEach(m =>
{
if (predicate != null && predicate(m))
{
matlist.Add(m);
}
});
});
return matlist.ToArray();
}
}
}