unity3d圣典脚本基础学习C#版本
基础内容常用操作Vector3 向量全局变量获取对象实例化
基础内容
所有脚本都继承自MonoBehaviour类;默认使用Start函数进行初始化,该函数仅执行一次。也可以使用Awake函数 进行初始化,不同之处在于 ,Awake在加载场景时运行,Start在 第一次调用Update或者FixedUpdate函数之前被调用,Awake运行在 Start函数之前。目前Unity暂不支持命名空间.或许未来版本会有.C#中协同程序有不同的句法规则,Coroutines必须是IEnumerator返回类型,并且yield用yield return替代.
using System
.Collections
;
using UnityEngine
;
public class NewBehaviourScript : MonoBehaviour
{
IEnumerator
SomeCoroutine () {
yield return 0;
yield return new WaitForSeconds (2);
}
}
常用操作
对物体的移动以及旋转通过Transfrom操作。
物体在Y轴上旋转5度。
public Transform transform
;
void Update()
{
transform
.Rotate(0,5,0);
transform
.Translate(0,0,2);
}
Vector3 向量
新建一个向量(1,1,1)
public Vector3 aposition
= new Vector3(1,1,1);
向量的点乘,一个向量在另一向量方向上的投影,一个数值
public Vector3 a
= new Vector3(1,1,1);
public Vector3 b
= new Vector3(1,0,1);
float result
= Vector3
.Dot(a
,b
);
向量的叉乘,得到一个垂直于两向量平面的新的向量
float result
= Vector3
.Cross(a
,b
);
两个向量夹角,范围[0,180]
float angle
= Vector3
.Angle(a
,b
);
两个向量距离
float dis
= Vector3
.Distance(a
,b
);
规范化单位向量不改变原向量
float dis
= Vector3
.Distance(a
.normalized
,b
.normalized
);
全局变量
用static关键字创建全局变量,这是创建了一个名为someGlobal的全局变量.
using UnityEngine
;
using System
.Collections
;
public class example : MonoBehaviour
{
public static int someGlobal
= 5;
public void Awake() {
print(typeof(someGlobal
));
typeof(someGlobal
) = 1;
}
}
从另一个脚本访问它,你需要用”脚本名加一个小圆点再加上全局变量名”.
print(TheScriptName
.someGlobal
);
TheScriptName
.someGlobal
= 10;
获取对象
通过对象名(字符串Cube)获取单个游戏对象
using UnityEngine
;
using System
.Collections
;
public class example : MonoBehaviour
{
public GameObject obj
;
void Start() {
obj
=GameObject
.Find("Cube");
}
void Update()
{
if(obj
!= null)
{
obj
.transform
.Rotate(0, Time
.deltaTime
* 200, 0);
}
}
}
通过标签获取多个/单个游戏对象
using UnityEngine
;
using System
.Collections
;
public class example : MonoBehaviour
{
public GameObject
[] obj
;
void Start() {
Myobjs
= GameObject
.FindGameObjectsWithTag("Cube");
}
void Update()
{
if(Myobjs
!= null)
{
foreach(GameObject obj
in Myobjs
)
{
Debug
.log("以"+obj
.tag
+"标签为游戏对象的名称"+obj
.name
);
}
}
}
实例化
一般创建克隆原始物体,多为预制体perfabs克隆原始物体,位置设置在position,设置旋转在rotation,返回的是克隆后的物体。这实际上在Unity和使用复制(ctrl+D)命令是一样的,并移动到指定的位置。如果一个游戏物体,组件或脚本实例被传入,实例将克隆整个游戏物体层次,以及所有子对象也会被克隆。所有游戏物体被激活。
public Transform prefab
;
void Start()
{
int i
= 0;
while(i
< 10)
{
Instantiate(prefab
,new Vector3(i
*2.0f
,0,0),Quaternion
.identity
);
i
++;
}
}
实例化更多通常用于实例投射物(如子弹、榴弹、破片、飞行的铁球等),AI敌人,粒子爆炸或破坏物体的替代品。
public Rigidbody obj
;
void Update()
{
Rigidbody clone
;
clone
= Instantiate(obj
,transform
.position
,transform
.rotation
);
}