unity3D -- 给游戏体添加组件

一、直接在编辑器Inspector上添加一个组件。

二、在脚本中使用AddComponent函数添加一个组件,例如:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
    private CanvasGroup m_CanvasGroup;
    void Start()
    {
        m_CanvasGroup = GetComponent ();
        if(m_CanvasGroup == null){
            gameObject.AddComponent ();
            m_CanvasGroup = GetComponent ();
        }
    }
}

官方实例:

    // Adds the sphere collider to the game object
    SphereCollider sc = gameObject.AddComponent("SphereCollider") as SphereCollider;
public Component AddComponent(Type componentType);

三、利用RequireComponent添加一个组件。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

[RequireComponent(typeof(CanvasGroup))]
[RequireComponent(typeof(Image))]
public class Test : MonoBehaviour {
    private CanvasGroup m_CanvasGroup;
    private Image m_Image;
    void Start()
    {
        m_CanvasGroup = GetComponent ();
        m_Image = GetComponent ();
    }
}

RequireComponent:这个类一定需要哪些组件,如果目前这些组件没有被加上,就自动加上。

官方实例:

using UnityEngine;
// The GameObject requires a Rigidbody component
[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
    Rigidbody rb;

    void Start() {
        rb = GetComponent();
    }
    void FixedUpdate()  {
        rb.AddForce(Vector3.up);
    }
}
public RequireComponent(Type requiredComponent);

public RequireComponent(Type requiredComponent, Type requiredComponent2);

public RequireComponent(Type requiredComponent, Type requiredComponent2, Type requiredComponent3);

–Rocky

你可能感兴趣的:(Unity3D)