[C#] MonoBehaviourExtended

Cette section est destinée aux scripts partagés par la communauté. Chaque post est destiné à un script. Suivez bien les recommandations.
Avatar de l’utilisateur
Greg
Messages : 156
Inscription : 08 Mai 2017 15:22

[C#] MonoBehaviourExtended

Message par Greg » 08 Mai 2017 21:41

Un petit script customisable pour rajouter des fonctions comme GetOrAddComponent, GetBrother ou ResetTransformation.

Code : Tout sélectionner

using UnityEngine;

// Methods Extension For MonoBehaviour
static public class MonoBehaviourExtended
{
    /// <summary>
    /// Gets or add a component. Usage example:
    /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
    /// </summary>
    static public T GetOrAddComponent<T>(this GameObject go) where T : Component
    {
        T result = go.GetComponent<T>();
        if (result == null)
        {
            result = go.AddComponent<T>();
        }
        return result;
    }

    /// <summary>
    /// Get Brother of object.
    /// gameobject.GetBrother("brotherName");
    /// </summary>
    static public GameObject GetBrother(this GameObject go, string brotherName)
    {
        GameObject currentBro = null;

        if (go.transform.parent == null)
            return currentBro;

        foreach (Transform child in go.transform.parent)
        {
            if (child.gameObject.name == brotherName)
            {
                currentBro = child.gameObject;
                return currentBro;
            }
        }

        return currentBro;
    }

    /// <summary>
    /// Enable/Disable GameObject. Usage example:
    /// gameobject.SetActiveToggle();
    /// </summary>
    static public void SetActiveToggle(this GameObject go)
    {
        go.SetActive(!go.activeSelf);
    }

    /// <summary>
    /// Clamp Vector3. Usage example:
    /// vector3.ClampVector3(vector3Min, vector3Max);
    /// </summary>
    static public Vector3 ClampVector3(this Vector3 vec, Vector3 min, Vector3 max)
    {
        return Vector3.Min(max, Vector3.Max(min, vec));
    }

    /// <summary>
    /// Clamp Vector2. Usage example:
    /// vector2.ClampVector2(vector2Min, vector2Max);
    /// </summary>
    static public Vector2 ClampVector2(this Vector2 vec, Vector2 min, Vector2 max)
    {
        return Vector2.Min(max, Vector2.Max(min, vec));
    }

    #region Example of extension method
    //https://unity3d.com/fr/learn/tutorials/topics/scripting/extension-methods
    public static void ResetTransformation(this Transform tr)
    {
        tr.position = Vector3.zero;
        tr.rotation = Quaternion.identity;
        tr.localScale = new Vector3(1, 1, 1);
    }
    #endregion
}
Mon jeu de développement cellulaire : MICROBIOME (encore quelques bugs...)
(merci bien à ceux qui passent mettre des étoiles ! ^^)

Répondre

Revenir vers « Scripts »