一、 项目内主要文件夹命名如下图所示:
依次存放:材质、模型、场景、脚本(代码)、Shader、贴图。
编码语言使用C#,代码编辑器推荐使用Visual Studio。
二、 代码
1. Unity3D中最重要的类:MonoBehaviour。
2.只有继承自MonoBehaviour的类才可以当作脚本,添加到GameObject上。
using UnityEngine;
using System.Collections;
public class TestScripts : MonoBehaviour
{
public float rotateSpeed01 = 1f;
protected float rotateSpeed02 = 1f;
private float rotateSpeed03 = 1f;
void Start()
{
}
void Update()
{
}
3.类中只有public的字段才会显示在Inspector面板上。
如果想让public的字段不显示在Inspector面板上,用[HideInInspector]。
如果想让protected或private的字段显示在Inspector面板上,用[SerializeField]。
using UnityEngine;
using System.Collections;
public class TestScripts : MonoBehaviour
{
[HideInInspector]
public float rotateSpeed01 = 1f;
[SerializeField]
protected float rotateSpeed02 = 1f;
[SerializeField]
private float rotateSpeed03 = 1f;
void Start()
{
}
void Update()
{
}
}
4.继承自MonoBehaviour的类,需要在代码里实例化的时候,不要用new去实例化,要用 AddComponent。
在继承自MonoBehaviour的类里,不要用构造函数和虚构函数;
要用Awake或Start。
Awake早于Start执行,然后再进入到Update和LateUpdate的循环中。
Unity3D生命周期官方的详细介绍: http://docs.unity3d.com/Manual/ExecutionOrder.html
5.协同程序:
IEnumerator IE_Function()
{
Debug.Log("开始");
yield return new WaitForSeconds(2f);
Debug.Log("过了两秒");
yield return new WaitForEndOfFrame();
Debug.Log("又过了一帧");
yield return null;
Debug.Log("还是过了一帧");
yield return new WaitForSeconds(1f);
Debug.Log("又过了1秒,并且此协同程序结束");
}
协同程序的启动
StartCoroutine("IE_Function");
//或者
StartCoroutine(IE_Function());
协同程序的强制停止
StopCoroutine("IE_Function");
//或者此方法可停止此脚本上的所有协同程序
StopAllCoroutines();
如果在协同程序中要检测Input中的事件时,
不能用yield return new WaitForEndOfFrame();
要用yield return null;
例如:
IEnumerator IE_Function()
{
Debug.Log("开始");
yield return new WaitForSeconds(2f);
Debug.Log("过了两秒");
while(true)
{
if(Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("您按下了键盘上的ESC键");
break;
}
//正确
yield return null;
//错误
//yield return new WaitForEndOfFrame();
Debug.Log("循环中...");
}
yield return new WaitForSeconds(1f);
Debug.Log("又过了1秒,并且此协同程序结束");
}