﻿using UnityEngine;

namespace JLGames.RocketDriver.Actions.Utils
{
    public static class ComponentUtil
    {
        /// <summary>
        /// Get component script by full name.
        /// 通过全名取组件脚本
        /// </summary>
        /// <param name="go"></param>
        /// <param name="scriptFullname"></param>
        /// <returns></returns>
        public static UnityEngine.Component GetComponentByName(GameObject go, string scriptFullname)
        {
            if (null == go || string.IsNullOrEmpty(scriptFullname)) return null;
            return go.GetComponent(scriptFullname);
        }

        /// <summary>
        /// Get component script by full name and convert it to type T.
        /// 通过全名取脚本，并转换为对应类型
        /// </summary>
        /// <param name="go"></param>
        /// <param name="scriptFullname"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetComponentByName<T>(GameObject go, string scriptFullname)
        {
            var script = GetComponentByName(go, scriptFullname);
            return CastComponent<T>(script);
        }

        /// <summary>
        /// Component type conversion
        /// 组件类型转换
        /// </summary>
        /// <param name="component"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T CastComponent<T>(UnityEngine.Component component)
        {
            if (null == component) return default(T);
            if (component is T)
            {
                return (T) (object) component;
            }

            return default(T);
        }
    }
}