unity3D实现给游戏体添加组件的实例

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

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

using UnityEngine;
using System.Collections;

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

官方实例:

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

3、利用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<CanvasGroup> ();
        m_Image = GetComponent<Image> ();
    }
}

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

官方实例:

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

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

public RequireComponent(Type requiredComponent, Type requiredComponent2);

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

 

未经允许不得转载:第一Unity3D » unity3D实现给游戏体添加组件的实例

赞 (0)