目录
(四)Unity函数的生命周期
(五)游戏组件获取与控制
首先先获取到该游戏物体,再通过GetComponent<T>()来获取游戏物体身上的组件。
gameObject.GetComponent<T>();
这个地方要注意避免空引用问题,所以在执行相关代码前,要增加一个if判断,如果获取的不为空蔡执行相关代码。
gameObject.AddComponent<T>();
删除组件
Destroy(某component);
组件失活/激活
某component.enabled = false; 某component.enabled = true ;
资源加载
GameObject obj=Resources.Load<GameObject>("Prefab/Tank") ;//这是将硬盘资源加载到内存中的一种方法,可以代替拖拽预制体到脚本的方法,前面加载个if判断可以避免重复执行提高效率。
Instantiate(obj);//在场景中实例化。
扩展学习:血条制作
public float xOffset;
public float yOffset;
public RectTransform recTransform;
void Update()
{
Vector2 player2DPosition = Camera.main.WorldToScreenPoint(transform.position);//将玩家世界坐标转换成屏幕坐标
recTransform.position = player2DPosition + new Vector2(xOffset, yOffset);//屏幕坐标加上偏移就得到UI坐标
//血条超出屏幕就不显示
if (player2DPosition.x > Screen.width || player2DPosition.x < 0 || player2DPosition.y > Screen.height || p