常用API和常见错误总结
APIUnity事件函数的执行时机和先后顺序void Awake(){Debug.Log("Awake");}void OnEnable(){Debug.Log("OnEnable");}public void CustomRethod(){Debug.Log("CustomRethod");}// Use this for initia...
API
Unity
事件函数的执行时机和先后顺序
void Awake()
{
Debug.Log("Awake");
}
void OnEnable()
{
Debug.Log("OnEnable");
}
public void CustomRethod()
{
Debug.Log("CustomRethod");
}
// Use this for initialization
void Start()
{
Debug.Log("Start");
}
void FixedUpdate()
{
Debug.Log("FixedUpdate");
}
// Update is called once per frame
void Update()
{
Debug.Log("Update");
}
void LateUpdate()
{
Debug.Log("LateUpate");
}
void OnApplicationPause(bool pause)
{
Debug.Log("OnApplicationPause");
}
void OnDisable()
{
Debug.Log("OnDisable ");
}
void OnApplicationQuit()
{
Debug.Log("OnApplicationQuit");
}
void Reset()
{
Debug.Log("reset");
}
void OnDestroy()
{
Debug.Log("OnDestory");
}
正常情况下调用顺序:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eb0Mcg7Q-1581865634970)(https://s2.ax1x.com/2019/05/14/EIAmzF.png)]
隐藏脚本时调用:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F094F9tr-1581865634972)(https://s2.ax1x.com/2019/05/14/EIAvwR.png)]
Time类中静态变量
//每帧时间间隔
Debug.Log("Time.deltaTime:" + Time.deltaTime);
//平滑的每帧时间间隔
Debug.Log("Time.smoothDeltaTime:" + Time.smoothDeltaTime);
//帧数
Debug.Log("Time.frameCount:" + Time.frameCount);
//游戏从开始运行的时间,游戏暂停也会继续计时
Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);
//游戏从开始运行的时间
Debug.Log("Time.time:" + Time.time);
Debug.Log("Time.fixedTime:" + Time.fixedTime);
Debug.Log("Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
//执行物理和其他固定帧速率更新的时间间隔
Debug.Log("Time.fixedDelTime:" + Time.fixedDeltaTime);
//时间比例,用来进行时间缩放
Debug.Log("Time.timeScale:" + Time.timeScale);
//自游戏开始以来的秒数,未缩放的固定时间,不受timeScale的影响
Debug.Log("Time.unscaledTime:" + Time.unscaledTime);
常用作用:
- Time.deltaTime:做运动和动画相关的事情
- Time.timeSinceLevelLoad:做性能测试
创建游戏物体的三种方法
//1.第一种创建方法
//GameObject go= new GameObject("Cube");
//2.第二种
//根据prefab
//根据另外一个游戏物体
GameObject.Instantiate(prefab);//可以根据prefab 或者 另外一个游戏物体克隆
//3.第三种 创建原始的几何体
GameObject.CreatePrimitive(PrimitiveType.Plane);
GameObject go=GameObject.CreatePrimitive(PrimitiveType.Cube);
通过代码给游戏物体添加组件
//给物体添加组件
go.AddComponent<Rigidbody>();
go.AddComponent<API01EventFunction>()
禁用和启用一个游戏物体
//activeInHierarchy返回物体是否被禁用,若是父物体被禁用,返回为false
Debug.Log(go.activeInHierarchy);
go.SetActive(false);
Debug.Log(go.activeInHierarchy);
//activeSelf返回物体是否被禁用,若是仅父物体被禁用,则返回true
Debug.Log(go.activeSelf);
//返回物体的标签,默认为untagged
Debug.Log(go.tag);
GameObject、Component和Object的关系
- 一个游戏由多个场景组成
- 一个场景由多个游戏物体(GameObject)组成
- 一个游戏物体由多个组件(Component)组成
组件包括:
Transform,Rigidbody,Mesh Render,MeshFilter,
Collider,NavmeshAgent,Animation,Animator,自定义的脚本
GameObject和Component继承自UnityEngine.Object,UnityEngine.Object继承自System.Object。
UnityEngine.Object
//输出绑定的物体的名字
Debug.Log(go.name);
Debug.Log(go.GetComponent<Transform>().name);
//删除游戏物体
Destroy(gameObject);
// Removes this script instance from the game object
Destroy(this);
// Removes the rigidbody from the game object
Destroy(GetComponent<Rigidbody>());
// Kills the game object in 5 seconds after loading the object
Destroy(gameObject, 5);
//立即删除游戏物体
DestroyImmediate(gameObject,true);
//public static void DontDestroyOnLoad(Object target);
//Do not destroy the target Object when loading a new Scene.
DontDestroyOnLoad(gameObject);
//通过组件获取对象
Light light = FindObjectOfType<Light>();
light.enabled = false;
Transform[] ts=FindObjectsOfType<Transform>();//不查找未激活的游戏物体
foreach (Transform t in ts)
{
Debug.Log(t);
}
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
GameObject
GameObject gameobj = GameObject.CreatePrimitive(PrimitiveType.Cube);
//遍历场景所有物体,超级耗费性能
GameObject go = GameObject.Find("Main Camera");
go.SetActive(false);
//根据标签返回一个数组
GameObject[] gos = GameObject.FindGameObjectsWithTag("Main Camera");
gos[0].SetActive(false);
//根据标签返回第一个物体
GameObject go1 = GameObject.FindGameObjectWithTag("Main Camera");
//当标签不存在时,报错Unity异常标签不存在;当标签存在但没有物体时,会报空引用异常
游戏物体间消息的发送和接收
GameObject和Component共有的方法
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
/// Calls the function ApplyDamage with a value of 5
/// // Every script attached to the game object and all its children
//广播:其子物体只要具有ApplyDamage方法都会被调用(除非SetActive为false)
// that has a ApplyDamage function will be called.
gameObject.BroadcastMessage("Attack",null,SendMessageOptions.DontRequireReceiver);
//只会调用目标身上的方法
gameObject.SendMessage("Attack",null,SendMessageOptions.DontRequireReceiver;
//从下自上调用,从当前物体到父类
gameObject.SendMessageUpwards("Attack",null,SendMessageOptions.DontRequireReceiver);
}
}
public class Example2 : MonoBehaviour
{
void Attack()
{
Debug.Log(this.gameObject+"Attack");
}
}
GetComponent //Returns the component of Type type if the game object has one attached, null if it doesn't.
GetComponentInChildren //Returns the component of Type type in the GameObject or any of its children using depth first search.
GetComponentInParent //Returns the component of Type type in the GameObject or any of its parents.
GetComponents //Returns all components of Type type in the GameObject.
GetComponentsInChildren //Returns all components of Type type in the GameObject or any of its children.
GetComponentsInParent //Returns all components of Type type in the GameObject or any of its parents.
MonoBehaviour总览
MonoBehaviour继承自Behaviour,Behaviour继承自Component。相当于MonoBehaviour间接继承了Component。
Properties
runInEditMode:在编辑器模式下运行,在类名上添加[ExecuteInEditMode]。
Public Methods
CancelInvoke //Cancels all Invoke calls on this MonoBehaviour.
Invoke //Invokes the method methodName in time seconds.
InvokeRepeating //Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.
IsInvoking //Is any invoke on methodName pending?
StartCoroutine //Starts a coroutine.
StopAllCoroutines //Stops all coroutines running on this behaviour.
StopCoroutine //Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.
Inherited Members
Properties
enabled //Enabled Behaviours are Updated, disabled Behaviours are not.
isActiveAndEnabled //Has the Behaviour had enabled called.
鼠标按下在射线接触点产生实例
using UnityEngine;
public class Test: MonoBehaviour
{
public GameObject cube;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
Instantiate(cube, hit.point, Quaternion.identity);
}
}
}
}
鼠标按下在一定距离产生实例
public class Test: MonoBehaviour
{
Vector3 mousePosition, targetPosition;
//To Instantiate TargetObject at mouse position
public Transform targetObject;
float distance = 10f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
mousePosition = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, distance));
targetObject.position = targetPosition;
//Debug.Log(mousePosition+" "+targetPosition);
if (Input.GetMouseButtonUp(0))
{
Instantiate(targetObject, targetObject.transform.position, targetObject.transform.rotation);
}
}
}
相隔一定帧数播放精灵动画
using UnityEngine;
public class Hero : MonoBehaviour {
public bool animation = true; //是否开启动画
public int frameCountPresconds = 10; //每秒播放几帧动画
public float timer = 0; //计时
public Sprite[] sprites; //精灵数组
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (animation)
{
timer += Time.deltaTime;
int frameIndex = (int)(timer / (1f / frameCountPresconds)); //1f/frameCountPresconds 1秒/每秒帧数=每帧动画的播放时间
int frame = frameIndex % 2;
gameObject.GetComponent<SpriteRenderer>().sprite = sprites[frame];
}
}
}
Animator
//match匹配
public void MatchTarget(Vector3 matchPosition, Quaternion matchRotation, AvatarTarget targetBodyPart, MatchTargetWeightMask weightMask, float startNormalizedTime, [Internal.DefaultValue("1")] float targetNormalizedTime);
//match匹配的位置和旋转选中
public MatchTargetWeightMask(Vector3 positionXYZWeight, float rotationWeight);
//IK动画
//位置绑定
public void SetIKPosition(AvatarIKGoal goal, Vector3 goalPosition);
//位置绑定权重
public void SetIKPositionWeight(AvatarIKGoal goal, float value);
//旋转绑定
public void SetIKRotation(AvatarIKGoal goal, Quaternion goalRotation);
//旋转绑定权重
public void SetIKRotationWeight(AvatarIKGoal goal, float value);
//获取动画状态
public AnimatorStateInfo GetCurrentAnimatorStateInfo(int layerIndex);
AnimatorStateInfo 动画器状态信息
bool loop;
bool IsName(string name);
bool IsTag(string tag);
AsyncOperation
//异步加载场景
AsyncOperation async = SceneManager.LoadSceneAsync(index);
//异步加载完成之后不激活场景
async.allowSceneActivation = false;
NavMeshAgent 导航网格代理
//计算路径:计算两点之间的路径并存储结果路径
public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path);
//寻找最近边缘:查找从导航网格上的点到最近的导航网格边缘。
public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int areaMask);
//暂停之后沿着当前路径重新恢复运动。
public void Resume();
//该代理沿着它的当前路径的刹车运动。
public void Stop();
//分配新路径给该代理。
public bool SetPath(NavMeshPath path);
//清除当前路径:当路径被清除,代理不会开始寻找新路径直到SetDestination 被调用。
public void ResetPath();
//设置或者更新目的地因此触发计算新的路径。
public bool SetDestination(Vector3 target);
//在导航网格中朝着目标方向追踪直线路径而不移动代理。
//该函数跟随代理位置和指定位置之间的射线路径。如果沿着路线遇到障碍,然后返回true值并且障碍对象的其他细节被存储进hit参数中。这可以用来检查是否有个清晰的镜头或者角色与目标对象之间的瞄准线。
public bool Raycast(Vector3 targetPosition, out NavMeshHit hit);
C#
Monitor
private static readonly object monitorLock = new object();
//Monitor Class:提供同步访问对象的机制。
//获取指定对象上的排他锁
System.Threading.Monitor.Enter(monitorLock); //加锁防止多线程创建单例
//如果另一个线程的对象已执行了Enter但尚未执行相应Exit,当前线程会阻塞,直到另一个线程释放对象。
//释放指定对象上的排他锁
System.Threading.Monitor.Exit(monitorLock);
Activator
//创建单例的实例
//使用无参数构造函数创建由指定泛型类型参数指定的类型的实例。
singleton = ((default(T) == null) ? Activator.CreateInstance<T>() : default);
错误
更多推荐
所有评论(0)