Unity3D常见技术点(持续更新)

时间:2023-03-08 23:27:39
Unity3D常见技术点(持续更新)

一:获取对象, 添加对象等

1:使用prefab生成对象

 GameObject ballObj = GameObject.Instantiate(Resources.Load("Fx/fx_bullet001"), 
transform.position + transform.forward * -0.8f + transform.up * ,
Quaternion.identity) as GameObject;

2:添加脚本到对象, 并更改脚本值

ballObj.AddComponent ("BasicGun");	

BasicGun pScript = ballObj.GetComponent ("BasicGun") as BasicGun;
pScript.player = playerObj;

  

3:在UIButton对象中获取 UIButton自身.

UISprite sprite = gameObject.GetComponentInChildren<UISprite> ();

  

二: 旋转相关

1:让一个对象与另一个对象的旋转角度一样(即朝向同一个方向)

// 主角的朝向
Vector3 dVector = playerObj.transform.forward; // 计算要旋转的角度
float testA = Mathf.Atan2(dVector.x, dVector.z);
testA = testA* Mathf.Rad2Deg; //本函数将 number 从弧度转换为角度 rad2deg(M_PI_4); // 45 // 对象旋转到对应角度
ballObj.transform.rotation = Quaternion.Euler(new Vector3(0, testA,0));

  ps: 不能直接为transform.rotation赋值。可以使用各种Quaternion的方法。

2: 旋转某对象的 方向

ballObj.transform.Rotate(Vector3.up, 30);

  

using UnityEngine;
using System.Collections; public class example : MonoBehaviour {
void Update() {
// Slowly rotate the object around its X axis at 1 degree/second.
//围绕x轴每秒1度,慢慢的旋转物体
transform.Rotate(Vector3.right, Time.deltaTime); // ... at the same time as spinning it relative to the global
// Y axis at the same speed.
//相对于世界坐标,围绕y轴每秒1度,慢慢的旋转物体
transform.Rotate(Vector3.up, Time.deltaTime, Space.World);
}
}

  

其他: