Unity学习笔记——C#初级编程
一、Awake 和 Start
Awake 和 Start 是在加载脚本时自动调用的两个函数,在一个对象绑定脚本的生命周期内只能调用一次。
Awake:还未启用脚本组件便已调用,适合用于在脚本与初始化之间设置任何引用
Start:在Awake之后调用,直接在首次更新之前调用,前提是已经启用了脚本组件,这样可以将初始化代码的任何部分,延迟到真正需要的时候再调用。
例如,有一个敌人进入游戏,并使用Awake获得了分配的弹药,但要想射击,需在启用脚本组件时,使用Start在定义时间实现射击。
using UnityEngine;
using System.Collections;
public class AwakeAndStart : MonoBehaviour
{
void Awake ()
{
Debug.Log("Awake called.");
}
void Start ()
{
Debug.Log("Start called.");
}
}
二、Update 和 FixedUpdate
Update:在每个使用它的脚本中每帧调用一次,基本上只要需要变化或调整都需要使用Update来实现。Update并不是按固定时间调用,如果某一帧比下一帧处理时间长,那么调用的时间间隔就会不同。
FixedUpdate:与Update类似,但FixedUpdate按固定时间调用,调用后会立即进行任何必要的物理计算,因此任何影响刚体(物理对象)的动作都应使用FixedUpdate执行。
using UnityEngine;
using System.Collections;
public class UpdateAndFixedUpdate : MonoBehaviour
{
void FixedUpdate ()
{
Debug.Log("FixedUpdate time :" + Time.deltaTime);
}
void Update ()
{
Debug.Log("Update time :" + Time.deltaTime);
}
}
Unity中的Update和其他许多特殊函数,都可以在Visual Studio中迅速轻松创建,使用MonoBehaviour脚本编写向导即可实现。按Ctrl+Shift+M启动向导,勾选想要添加的方法即可在光标处添加函数。
三、启用和禁用组件
只需使用enabled标记,设为false即可禁用组件。
注意,脚本也是组件,也可以通过enabled禁用。
using UnityEngine;
using System.Collections;
public class EnableComponents : MonoBehaviour
{
private Light myLight;
void Start ()
{
myLight = GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))//按下空格
{
myLight.enabled = !myLight.enabled;
}
}
}
四、SetActive、Active Self、Active in Hierarchy
SetActive:通过脚本在场景中激活或停用对象。需要注意的是,停用父对象,那么场景中活跃的子对象也会停止,但子对象仍在其层次结构中保持活跃状态。下图例子中,停用父对象PhysicsDoor,子对象Door变灰,但在层次结构中仍旧保持活跃状态。
SetActive示例——停用对象
------------------------------------------------------
using UnityEngine;
using System.Collections;
public class ActiveObjects : MonoBehaviour
{
void Start ()
{
gameObject.SetActive(false);
}
}
------------------------------------------------------
Active Self:检测对象在场景中是否处于活跃状态。
Active in Hierarchy:检测对象在层次结构中是否处于活跃状态。
Active Self、Active in Hierarchy示例——输出对象状态
-----------------------------------------------------------------------
using UnityEngine;
using System.Collections;
public class CheckState : MonoBehaviour
{
public GameObject myObject;
void Start ()
{
Debug.Log("Active Self: " + myObject.activeSelf);
Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
}
}
----------------