unity3D -- 給遊戲體新增元件
阿新 • • 發佈:2019-01-28
一、直接在編輯器Inspector上新增一個元件。
二、在指令碼中使用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);
三、利用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
[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);
–Rocky