Unity3D给游戏体添加组件的方法
发表于2018-09-27
在Unity3D中,组件就是组成游戏世界的最基本元素,这篇内容主要给大家分享三种给游戏体添加组件的方法,希望能对大家有帮助。
一、直接在编辑器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);