1. 类定义了-- 属性和方法 ---可以实例化为具体的对象
public class Person
{
// 属性(数据)
public string Name;
public int Age;
// 方法(行为)
public void SayHello()
{
Console.WriteLine("Hello, my name is " + Name + " and I'm " + Age + " years old.");
}
}
2.在其他的代码调用时---先实例化类--对象
Person person = new Person();
person.Name = "John";
person.Age = 25;
person.SayHello(); // 输出:Hello, my name is John and I'm 25 years old.
3.在类里面构造函数--一定要和类的名字一样 --一定不能有返回值--对象初始只调用一个构造函数
public Person(string A, int B)
{
name = A;
age = B
}
4.如果用两个构造函数
//第一个构造函数
public Person person = new Person(A,B);
//第二个构造函数
public Person otherPerson = new Person(C,D,E)
二:生成克隆--先实例化
public Rigidbody projectile;
public Transform ShengCheng;
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
//生成什么 生成位置 生成角度
Instantiate(projectile, ShengCheng.position, ShengCheng.rotation);
}
强制转换--Instantiate(projectile, ShengCheng.position, ShengCheng.rotation) as Rigidbody
Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * 5000);
三: 使用Invoke 函数---延后性,在几秒后执行
using UnityEngine;
using System.Collections;
public class InvokeScript : MonoBehaviour
{
public GameObject target;
void Start()
{
//两秒之后执行--这个方法--方法必须是void
Invoke ("SpawnObject", 2);
}
//生成target--在这个位置
void SpawnObject()
{
Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
//Quaternion.identity表示没有任何旋转的四元数,它的值为(0, 0, 0, 1)。
}
}
四:枚举
1.我们可以将枚举放在类中--这个类必须访问这个枚举
可以给每一个变量赋值--以便调用
enum Direction {North,East=10,South=2,West};
//可以改变枚举的变量类型
enum Direction : string {North,East=10,South=2,West};
2.创建一个枚举的变量
Direction myDirection;
五--Switch
public class ConversationScript : MonoBehaviour
{
public int intelligence = 5;
void Greet()
{
switch (intelligence)
{
case 5:
print ("Why hello there good sir! Let me teach you about Trigonometry!");
break;
case 4:
print ("Hello and good day!");
break;
case 3:
print ("Whadya want?");
break;
case 2:
print ("Grog SMASH!");
break;
case 1:
print ("Ulg, glib, Pblblblblb");
break;
default:
print ("Incorrect intelligence level.");
break;
}
}
}