Unity目前的最新版本是5.5.2,可横跨9种主要游戏平台,包括Web平台,PC平台,Mac平台,IOS平台,Flash平台,Android平台,Xbox 360平台,PS3平台和Wii平台。
pdf源码下载:http://www.ituring.com.cn/book/1015
引擎下载:http://unity3d.com/unity/download/
Unity5.5系统的标准资源包导入,在Project右键,”Import Package”-“Characters”
1.Unity中包含5大视图,分别是Scene(场景)视图、Game(游戏)视图、Hierarchy(层次)视图、Project(项目)视图和Inspector(监测)视图。视图与视图之间保持非常紧密的联系。
创建完资源后,它将保存在工程根目录下的“Assets”文件夹中。
//模型移动速度
var TranslateSpeed = 20;
//模型旋转速度
var RotateSpeed = 1000;
function OnGUI() {
//设置GUI背景颜色
GUI.backgroundColor = Color.red;
if (GUI.Button(Rect(10, 10, 70, 30), "向左旋转")) {
//向左旋转模型
transform.Rotate(Vector3.up * Time.deltaTime * (-RotateSpeed));
}
if (GUI.Button(Rect(90, 10, 70, 30), "向前移动")) {
//向前移动模型
transform.Translate(Vector3.forward * Time.deltaTime * TranslateSpeed);
}
if (GUI.Button(Rect(170, 10, 70, 30), "向右旋转")) {
//向右旋转模型
transform.Rotate(Vector3.up * Time.deltaTime * RotateSpeed);
}
if (GUI.Button(Rect(90, 50, 70, 30), "向后移动")) {
//向后移动模型
transform.Translate(Vector3.forward * Time.deltaTime * (-TranslateSpeed));
}
if (GUI.Button(Rect(10, 50, 70, 30), "向左移动")) {
//向左移动模型
transform.Translate(Vector3.right * Time.deltaTime * (-TranslateSpeed));
}
if (GUI.Button(Rect(170, 50, 70, 30), "向右移动")) {
//向右移动模型
transform.Translate(Vector3.right * Time.deltaTime * TranslateSpeed);
}
//显示模型位置信息
GUI.Label(Rect(250, 10, 200, 30), "模型的位置" + transform.position);
//显示模型旋转信息
GUI.Label(Rect(250, 50, 200, 30), "模型的旋转" + transform.rotation);
}
function Start () {
}
function Update () {
//该方法每一帧都会调用
}
//接收外部赋值字符串
var str:String;
//接收外部赋值贴图
var imageTexture:Texture;
//贴图宽度
private var imageWidth: int;
//贴图高度
private var imageHeight: int;
//当前屏幕宽度
private var screenWidth: int;
//当前屏幕高度
private var screenHeight: int;
function Start() {
//只执行一次,界面初始化
//得到屏幕宽高
screenWidth = Screen.width;
screenHeight = Screen.height;
//得到图片宽高
imageWidth = imageTexture.width;
imageHeight = imageTexture.height;
}
function OnGUI() {
//界面绘制方法,所有GUI的绘制都需要在这个方法中实现
//将文字内容显示在屏幕中
GUI.Label(Rect(100, 10, 100, 30), str);
GUI.Label(Rect(100, 40, 100, 30), "当前屏幕宽:" + screenWidth);
GUI.Label(Rect(100, 80, 100, 30), "当前屏幕高:" + screenHeight);
//将贴图显示在屏幕中
GUI.Label(Rect(100,120,imageWidth,imageHeight),imageTexture);
}
function Update () {
}
//按钮贴图
var buttonTexture : Texture2D;
//提示信息
private var str:String;
//时间计数器
private var frameTime:int;
function Start () {
//初始化赋值
str = "请您点击按钮";
}
function Update () {
}
function OnGUI(){
//显示提示信息内容
GUI.Label(Rect(10,10,Screen.width,30),str);
if(GUI.Button(Rect(10,50,buttonTexture.width,buttonTexture.height),buttonTexture)){
//点击按钮修改提示信息
str = "您点击了图片按钮";
}
//设置按钮中文字的颜色
GUI.color = Color.green;
//设置按钮的背景色
GUI.backgroundColor = Color.red;
if(GUI.Button(Rect(10,200,70,30),"文字按钮")){
//点击按钮修改提示信息
str = "您点击了文字按钮";
}
//设置按钮中文字的颜色
GUI.color = Color.yellow;
//设置按钮的背景色
GUI.backgroundColor = Color.black;
if(GUI.Repeat(Rect(10,250,100,30),"按钮按下中")){
//点击按钮修改提示信息
str = "按钮按下中的时间:"+frameTime;
//时间计数器
frameTime++;
}
}
该实例获取用户输入的用户名和密码并显示
//用户名
private var editUsername:String;
//密码
private var editPassword:String;
//提示信息
private var editShow:String;
function Start () {
editShow = "请您输入正确的用户名和密码";
editUsername = "请输入用户名";
editPassword = "请输入密码";
}
function Update () {
}
function OnGUI(){
//显示提示信息内容
GUI.Label(Rect(10,10,Screen.width,30),editShow);
if(GUI.Button(Rect(10,120,100,50),"登录")){
//点击按钮修改提示信息
editShow = "您输入的用户名为:"+editUsername + "您输入的密码为:"+editPassword;
}
//编辑框提示信息
GUI.Label(Rect(10,40,50,30),"用户名");
GUI.Label(Rect(10,80,50,30),"密码");
//获取输入框输入的内容
editUsername = GUI.TextField(Rect(60,40,200,30),editUsername,15);
editPassword = GUI.PasswordField(Rect(60,80,200,30),editPassword,"*"[0],15);
}
该实例通过点击不同按钮来回切换界面显示的内容,并且内容以单选项的形式呈现出来
//工具栏选择按钮的ID
private var select:int;
//工具栏显示按钮的字符串
private var barResource:String[];
//选择按钮是否被按下
private var selectToggle0:boolean;
private var selectToggle1:boolean;
function Start () {
//初始化
select = 0;
barResource = ["第一个工具栏","第二个工具栏","第三个工具栏","第四个工具栏"];
selectToggle0 = false;
selectToggle1 = false;
}
function Update () {
}
function OnGUI(){
//备份上一次工具栏选择的ID
var oldSelect = select;
//重新计算本次工具栏选择的ID
select = GUI.Toolbar(Rect(10,10,barResource.length*100,30),select,barResource);
//如果两次选择的是不同的工具栏,将选择按钮全部释放掉
if(oldSelect!=select){
selectToggle0 = false;
selectToggle1 = false;
}
//根据工具栏选择的ID显示不同的信息
switch(select){
case 0:
selectToggle0 = GUI.Toggle(Rect(10,50,150,30),selectToggle0,"第一个工具栏单项选择——1");
selectToggle1 = GUI.Toggle(Rect(10,80,150,30),selectToggle1,"第一个工具栏单项选择——2");
break;
case 1:
selectToggle0 = GUI.Toggle(Rect(10,50,150,30),selectToggle0,"第二个工具栏单项选择——1");
selectToggle1 = GUI.Toggle(Rect(10,80,150,30),selectToggle1,"第二个工具栏单项选择——2");
break;
case 2:
selectToggle0 = GUI.Toggle(Rect(10,50,150,30),selectToggle0,"第三个工具栏单项选择——1");
selectToggle1 = GUI.Toggle(Rect(10,80,150,30),selectToggle1,"第三个工具栏单项选择——2");
break;
case 3:
selectToggle0 = GUI.Toggle(Rect(10,50,150,30),selectToggle0,"第四个工具栏单项选择——1");
selectToggle1 = GUI.Toggle(Rect(10,80,150,30),selectToggle1,"第四个工具栏单项选择——2");
break;
}
}
//纵向滑动条数值
var verticalValue:int = 0;
//横向滑动条数值
var horizontalValue:float = 0.0f;
function OnGUI(){
//计算滑动速度
verticalValue = GUI.VerticalSlider(Rect(25,25,30,100),verticalValue,100,0);
horizontalValue = GUI.HorizontalSlider(Rect(50,25,100,30),horizontalValue,0.0f,100.0f);
//将滑动进度显示在屏幕中
GUI.Label(Rect(10,150,Screen.width,30),"纵向滑动条当前进度:"+verticalValue+"%");
GUI.Label(Rect(10,180,Screen.width,30),"横向滑动条当前进度:"+horizontalValue+"%");
}
function Start () {
}
function Update () {
}
//滚动条位置
var scrollPosition:Vector2;
function Start () {
//初始化滚动条位置
scrollPosition[0] = 50;
scrollPosition[1] = 50;
}
function OnGUI(){
//开始滚动视图
scrollPosition = GUI.BeginScrollView(Rect(0,0,200,200),scrollPosition,Rect(0,0,Screen.width,300),true,true);
GUI.Label(Rect(100,40,Screen.width,30),"测试滚动视图,测试滚动视图,测试滚动视图,测试滚动视图,测试滚动视图。");
//结束滚动条视图
GUI.EndScrollView();
}
function Update () {
}
//贴图
var viewTexture0:Texture2D;
var viewTexture1:Texture2D;
function Start () {
}
function OnGUI(){
//开始这个群组
GUI.BeginGroup(new Rect(10,50,200,400));
//显示贴图,坐标为相对群组的点(10,50)的坐标
GUI.DrawTexture(Rect(10,20,viewTexture0.width,viewTexture0.height),viewTexture0);
//标签提示信息
GUI.Label(Rect(10,150,100,40),"群组视图1");
//按钮
GUI.Button(Rect(10,190,100,40),"按钮");
//结束这个群组
GUI.EndGroup();
//开始这个群组
GUI.BeginGroup(new Rect(300,0,500,400));
//显示贴图,坐标为相对群组的点(300,0)的坐标
GUI.DrawTexture(Rect(10,20,viewTexture1.width,viewTexture1.height),viewTexture1);
//标签提示信息
GUI.Label(Rect(10,150,100,40),"群组视图2");
//按钮
GUI.Button(Rect(10,190,100,40),"按钮");
//结束这个群组
GUI.EndGroup();
}
function Update () {
}
//默认窗口位置
private var window0 : Rect = Rect(20,20,200,200);
private var window1 : Rect = Rect(250,20,200,200);
function Start () {
}
function OnGUI(){
//在这里注册两个窗口
GUI.Window(0,window0,oneWindow,"第一个窗口");
GUI.Window(1,window1,twoWindow,"第二个窗口");
}
//显示窗口1的内容
function oneWindow(windowID:int){
GUI.Box(Rect(10,50,150,50),"这里窗口的ID是"+windowID);
if(GUI.Button(Rect(10,120,150,50),"普通按钮")){
Debug.Log("窗口ID="+windowID+"按钮被点击");
}
}
//显示窗口2的内容
function twoWindow(windowID:int){
GUI.Box(Rect(10,50,150,50),"这里窗口的ID是"+windowID);
if(GUI.Button(Rect(10,120,150,50),"普通按钮")){
Debug.Log("窗口ID="+windowID+"按钮被点击");
}
}
function Update () {
}
//自定义皮肤
var mySkin : GUISkin;
//单选控件是否被选中
private var choose : boolean = false;
//拖动窗口的位置
var windowRect : Rect = Rect(20,20,120,50);
//拖动窗口的位置
var edit : String = "请输入字符串";
function Start () {
}
function OnGUI(){
//设置GUI皮肤为自定义皮肤
GUI.skin = mySkin;
//绘制自定义按钮
GUI.Button(Rect(100,100,100,100),"自定义按钮");
//单项选择
choose = GUI.Toggle(Rect(10,50,100,30),choose,"单向选择");
//输入框
edit = GUI.TextField(Rect(200,10,200,20),edit,25);
//注册窗口
windowRect = GUI.Window(0,windowRect,setWindow,"这是一个窗口");
}
//创建窗口内容
function setWindow(windowID : int){
//创建一个可以自由拖动的窗口
GUI.DragWindow();
//绘制自定义按钮
GUI.Button(Rect(10,20,100,30),"自定义按钮");
}
function Update () {
}
//自定义皮肤
var mySkin : GUISkin;
function Start () {
}
function OnGUI(){
//设置GUI皮肤为我们自定义的皮肤
GUI.skin = mySkin;
//绘制按钮,通过名称找到对应风格
GUI.Button(Rect(0,100,300,100),"Custom0","Custom0");
GUI.Button(Rect(300,100,300,100),"Custom1","Custom1");
}
function Update () {
}
var addStr : String = "添加测试字符串";
function OnGUI(){
//普通GUI按钮
if(GUI.Button(Rect(50,50,100,30),addStr)){
addStr += addStr;
}
//界面布局按钮
if(GUILayout.Button(addStr)){
addStr += addStr;
}
}
function OnGUI(){
//默认垂直线性排列
GUILayout.Button("设置按钮布局宽度为400,高度为30",
GUILayout.Width(400),GUILayout.Height(30));
GUILayout.Label("设置按钮布局宽度为500,高度为30",
GUILayout.Width(500),GUILayout.Height(30));
GUILayout.Button("设置按钮布局宽度为100,高度为20",
GUILayout.Width(100),GUILayout.Height(20));
GUILayout.Button("设置按钮布局宽度为400,高度为40",
GUILayout.Width(400),GUILayout.Height(40));
//设置的width中最大的宽度,不一定是Button,这里最大是Label的500
GUILayout.Button("设置宽度不等于最宽按钮",GUILayout.ExpandWidth(false));
GUILayout.Button("设置宽度等于最宽按钮",GUILayout.ExpandWidth(true));
}
//贴图
var texture : Texture2D;
function OnGUI(){
//开始水平线性布局
GUILayout.BeginHorizontal();
GUILayout.Box("开始水平布局");
GUILayout.Button("按钮");
GUILayout.Label("文本框");
GUILayout.TextField("输入框");
GUILayout.Box(texture);
//结束水平线性布局
GUILayout.EndHorizontal();
//开始垂直线性布局
GUILayout.BeginVertical();
GUILayout.Box("开始垂直布局");
GUILayout.Button("按钮");
GUILayout.Label("文本框");
GUILayout.TextField("输入框");
GUILayout.Box(texture);
//结束垂直线性布局
GUILayout.EndVertical();
}
function OnGUI(){
//开始一个显示区域
GUILayout.BeginArea(Rect(0,0,200,60));
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
GUILayout.Box("Test1");
//两个Box控件中间偏移10像素
GUILayout.Space(10);
GUILayout.Box("Test2");
GUILayout.EndVertical();
//两个纵向布局中间偏移20像素
GUILayout.Space(20);
GUILayout.BeginVertical();
GUILayout.Box("Test3");
//两个Box控件中间偏移10像素
GUILayout.Space(10);
GUILayout.Box("Test4");
GUILayout.EndVertical();
GUILayout.EndHorizontal();
//结束显示区域
GUILayout.EndArea();
}
function OnGUI(){
GUILayout.BeginArea(Rect(0,0,Screen.width,Screen.height));
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
GUILayout.Box("Test1");
//两个Box控件上下对齐
GUILayout.FlexibleSpace();
GUILayout.Box("Test2");
GUILayout.EndVertical();
//布局之间左右对齐
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.Box("Test3");
//两个Box控件上下对齐
GUILayout.FlexibleSpace();
GUILayout.Box("Test4");
GUILayout.EndVertical();
GUILayout.EndHorizontal();
//结束显示区域
GUILayout.EndArea();
}
//使用ArrayList存储窗口
var winArrayList = new ArrayList();
//图标
var icon : Texture;
function Start(){
//添加一个窗口
winArrayList.Add(Rect(winArrayList.Count*100,50,150,100));
}
function OnGUI(){
//遍历每个窗口,并且加入视图
var count = winArrayList.Count;
for(var i = 0;i"窗口ID:"+i);
}
}
function AddWindow(windowID:int){
GUILayout.BeginHorizontal();
GUILayout.Label(icon,GUILayout.Width(50),GUILayout.Height(50));
GUILayout.Label("这是一个全新的窗口");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if(GUILayout.Button("添加新窗口")){
//添加窗口
winArrayList.Add(Rect(winArrayList.Count*100,50,50,100));
}
if(GUILayout.Button("关闭当前窗口")){
//关闭窗口
winArrayList.RemoveAt(windowID);
}
GUILayout.EndHorizontal();
GUI.DragWindow(Rect(0,0,Screen.width,Screen.height));
}
//皮肤
var mySkin : GUISkin;
function OnGUI(){
//设置皮肤
GUI.skin = mySkin;
GUILayout.Box("华为仿宋");
GUILayout.Button("华为彩云");
GUILayout.Label("默认字体");
}
Unity脚本默认的编码是Western(ISO latin 1),这种编码是不支持中文的。为了可以正常显示中文,我们需要修改脚本的编码格式。JavaScript需要将脚本编码格式修改为Unicode(UTF-8),C#需要将脚本编码格式修改为Unicode(UTF-16)。
//贴图
private var textSingle : Texture2D;
//贴图数组
private var textAll : Object[];
function OnGUI(){
if(GUI.Button(Rect(0,10,100,50),"加载一张贴图")){
if(textSingle == null){
//加载贴图
textSingle = Resources.Load("single/0");
}
}
if(GUI.Button(Rect(0,130,100,50),"加载一组贴图")){
if(textAll == null){
//加载所有贴图
textAll = Resources.LoadAll("Textures");
}
}
//绘制贴图
if(textSingle != null){
//绘制一张贴图
GUI.DrawTexture(Rect(110,10,120,120),textSingle,ScaleMode.StretchToFill,true,0);
}
if(textAll != null){
for(var i = 0;i//绘制贴图
GUI.DrawTexture(Rect(110+i*120,130,120,120),textAll[i],ScaleMode.StretchToFill,true,0);
}
}
}
//动画数组
private var anim : Object[];
//帧序列
private var nowFram : int;
//动画帧的总数
private var mFrameCount : int;
//限制一秒多少帧
private var fps : float = 15;
//限制帧的时间
private var time : float = 0;
function Start(){
//得到帧动画中的所有图片资源
anim = Resources.LoadAll("animation");
//得到该动画共有多少帧
mFrameCount = anim.length;
}
function OnGUI(){
//绘制帧动画
DrawAnimation(anim,Rect(100,100,50,100));
}
function DrawAnimation(tex:Object[],rect:Rect){
//绘制动画信息
GUILayout.Label("当前动画播放:第"+nowFram+"帧");
//绘制当前帧
GUI.DrawTexture(rect,tex[nowFram],ScaleMode.StretchToFill,true,0);
//计算限制帧时间
time += Time.deltaTime;
//超过限制帧则切换图片
if(time >= 1.0/fps){
//帧序列切换
nowFram++;
//限制帧清空
time = 0;
//超过帧动画总数,从第0帧开始
if(nowFram >= mFrameCount){
nowFram = 0;
}
}
}
//动画数组
private var animUp : Object[];
private var animDown : Object[];
private var animleft : Object[];
private var animRight : Object[];
//地图贴图
private var map : Texture2D;
//当前人物动画
private var tex : Object[];
//人物的x坐标
private var x : int;
//人物的y坐标
private var y : int;
//帧序列
private var nowFram : int;
//动画帧的总数
private var mFrameCount : int;
//限制一秒多少帧
private var fps : float = 15;
//限制帧的时间
private var time : float = 0;
function Start () {
//得到帧动画中的所有图片资源
animUp = Resources.LoadAll("animation");
animDown = Resources.LoadAll("animation");
animleft = Resources.LoadAll("animation");
animRight = Resources.LoadAll("animation");
//得到地图资源
map = Resources.Load("map/map");
//设置默认动画
tex = animUp;
}
function OnGUI(){
//绘制贴图
GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height),map,
ScaleMode.StretchToFill,true,0);
//绘制帧动画
DrawAnimation(tex,Rect(x,y,50,100));
//点击按钮移动人物
if(GUILayout.RepeatButton("向上")){
y-=2;
tex = animUp;
}
if(GUILayout.RepeatButton("向下")){
y+=2;
tex = animDown;
}
if(GUILayout.RepeatButton("向左")){
x-=2;
tex = animleft;
}
if(GUILayout.RepeatButton("向右")){
x+=2;
tex = animRight;
}
}
function DrawAnimation(tex:Object[],rect:Rect){
//绘制当前帧
GUI.DrawTexture(rect,tex[nowFram],ScaleMode.StretchToFill,true,0);
//计算限制帧时间
time += Time.deltaTime;
//超过限制帧则切换图片
if(time >= 1.0/fps){
//帧序列切换
nowFram++;
//限制帧清空
time = 0;
//超过帧动画总数,从第0帧开始
if(nowFram >= tex.Length){
nowFram = 0;
}
}
}
//主角对象
private var hero : GameObject;
//按键是否被按下
private var keyUp : boolean;
private var keyDown : boolean;
private var keyLeft : boolean;
private var keyRight : boolean;
//记录当前时间
private var time : float;
//限制一秒多少帧
private var fps : float = 10;
//帧序列
private var nowFram : int;
//动画数组
private var animUp : Object[];
private var animDown : Object[];
private var animleft : Object[];
private var animRight : Object[];
private var nowAnim : Object[];
private var backAnim : Object[];
function Start () {
//得到主角对象
hero = GameObject.Find("hero");
//得到上下左右四组动画
animUp = Resources.LoadAll("animation");
animDown = Resources.LoadAll("animation");
animleft = Resources.LoadAll("animation");
animRight = Resources.LoadAll("animation");
nowAnim = animDown;
backAnim = animDown;
}
function OnGUI(){
//控制主角移动的按钮
keyUp = GUILayout.RepeatButton("向上");
keyDown = GUILayout.RepeatButton("向下");
keyLeft = GUILayout.RepeatButton("向左");
keyRight = GUILayout.RepeatButton("向右");
}
function FixedUpdate () {
if(keyUp){
//向上移动
SetAnimation(animUp);
hero.transform.Translate(-Vector3.forward*1f);
}
if(keyDown){
//向下移动
SetAnimation(animDown);
hero.transform.Translate(Vector3.forward*1f);
}
if(keyLeft){
//向左移动
SetAnimation(animleft);
hero.transform.Translate(Vector3.right*1f);
}
if(keyRight){
//向右移动
SetAnimation(animRight);
hero.transform.Translate(-Vector3.right*1f);
}
//播放动画
DrawAnimation(nowAnim);
}
function DrawAnimation(tex:Object[]){
//计算限制帧时间
time += Time.deltaTime;
//超过限制帧则切换图片
if(time >= 1.0/fps){
//帧序列切换
nowFram++;
//限制帧清空
time = 0;
//超过帧动画总数,从第0帧开始
if(nowFram >= tex.Length){
nowFram = 0;
}
}
//将对应的贴图赋予主角对象
hero.GetComponent(Renderer).material.mainTexture = tex[nowFram];
}
function SetAnimation(tex:Object[]){
//设置播放动画
nowAnim = tex;
if(!backAnim.Equals(nowAnim)){
nowFram = 0;
backAnim = nowAnim;
}
}
//背景贴图
private var bg : Texture2D;
//标题贴图
private var title : Texture2D;
//动画数组
private var tex : Object[];
//动画x坐标
private var x : int;
//动画y坐标
private var y : int;
//帧序列
private var nowFram : int;
//动画帧的总数
private var mFrameCount : int;
//限制一秒多少帧
private var fps : float = 5;
//限制帧的时间
private var time : float = 0;
function Start(){
//载入资源
bg = Resources.Load("map/map");
title = Resources.Load("single/0");
tex = Resources.LoadAll("animation");
//初始化动画坐标
x = Screen.width;
y = 200;
}
function OnGUI(){
//绘制贴图
GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height),bg,
ScaleMode.StretchToFill,true,0);
//绘制标题
GUI.DrawTexture(Rect((Screen.width-title.width)>>1,30,title.width,title.height),title,
ScaleMode.StretchToFill,true,0);
//绘制帧动画
DrawAnimation(tex,Rect(x,y,40,60));
//动画越界监测
x --;
if(x<-42){
x = 480;
}
//绘制按钮
GUI.Button(Rect(500,200,100,30),"开始游戏");
GUI.Button(Rect(500,240,100,30),"读取进度");
GUI.Button(Rect(500,280,100,30),"关于游戏");
GUI.Button(Rect(500,320,100,30),"退出游戏");
}
function DrawAnimation(tex:Object[],rect : Rect){
//绘制当前帧
GUI.DrawTexture(rect,tex[nowFram],ScaleMode.StretchToFill,true,0);
//计算限制帧时间
time += Time.deltaTime;
//超过限制帧则切换图片
if(time >= 1.0/fps){
//帧序列切换
nowFram++;
//限制帧清空
time = 0;
//超过帧动画总数,从第0帧开始
if(nowFram >= tex.Length){
nowFram = 0;
}
}
}
function OnGUI(){
if(GUILayout.Button("创建立方体",GUILayout.Height(50))){
//设置该模型默认为立方体
var objCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
//给此对象添加一个刚体,用于物理感应
objCube.AddComponent(Rigidbody);
//设置这个游戏对象的名称
objCube.name = "Cube";
//设置此模型材质的颜色
objCube.GetComponent(Renderer).material.color = Color.blue;
//设置此模型的坐标
objCube.transform.position = new Vector3(0.0f,10.0f,0.0f);
}
if(GUILayout.Button("创建球体",GUILayout.Height(50))){
//设置该模型默认为球体
var objSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
//给此对象添加一个刚体,用于物理感应
objSphere.AddComponent(Rigidbody);
//设置这个游戏对象的名称
objSphere.name = "Sphere";
//设置此模型材质的颜色
objSphere.GetComponent(Renderer).material.color = Color.red;
//设置此模型的坐标
objSphere.transform.position = new Vector3(0.0f,10.0f,0.0f);
}
}
//立方体对象
private var objCube : GameObject;
//球体对象
private var objSphere : GameObject;
//是否旋转立方体
private var isCubeRotate = false;
//是否旋转球体
private var isSphereRotate = false;
//按钮提示信息
private var CubeInfo : String = "旋转立方体";
private var SphereInfo : String = "旋转球体";
function Start(){
//获取游戏对象
objCube = GameObject.Find("Cube");
objSphere = GameObject.Find("Object/Sphere");
}
function Update(){
//用户点击"旋转立方体"按钮时旋转模型
if(isCubeRotate){
//当立方体对象不为null时旋转
if(objCube){
objCube.transform.Rotate(0.0f,Time.deltaTime*200,0.0f);
}
}
//用户点击"旋转球体"按钮时旋转模型
if(isSphereRotate){
//当球体对象不为null时旋转
if(objSphere){
objSphere.transform.Rotate(0.0f,Time.deltaTime*200,0.0f);
}
}
}
function OnGUI(){
//添加用于旋转立方体的按钮
if(GUILayout.Button(CubeInfo,GUILayout.Height(50))){
if(!isCubeRotate){
isCubeRotate = true;
CubeInfo = "停止旋转立方体";
}else{
isCubeRotate = false;
CubeInfo = "旋转立方体";
}
}
//添加用于旋转球体的按钮
if(GUILayout.Button(SphereInfo,GUILayout.Height(50))){
if(!isSphereRotate){
isSphereRotate = true;
SphereInfo = "停止旋转球体";
}else{
isSphereRotate = false;
SphereInfo = "旋转球体";
}
}
//添加用于销毁游戏对象的按钮
if(GUILayout.Button("立即销毁模型",GUILayout.Height(50))){
//立即销毁立方体与球体对象
Destroy(objCube);
Destroy(objSphere);
}
}
//立方体对象
private var objCube : GameObject;
function Start(){
//获取添加过"MyTag"标签的游戏对象
objCube = GameObject.FindWithTag("MyTag");
}
function Start () {
//得到包含MyTag标签的游戏对象数组
var objs = GameObject.FindGameObjectsWithTag("MyTag");
//将5号元素的标签名称修改为TestTag
objs[5].tag = "TestTag";
//遍历所有游戏对象
for(var obj in objs){
Debug.Log("以"+obj.tag+"标签为游戏对象的名称"+obj.name);
//判断标签的名称是否为TestTag
if(obj.tag == "TestTag"){
Debug.Log("这个标签为TestTag");
}
//判断该游戏对象是否包含TestTag这个标签
if(obj.CompareTag("TestTag")){
Debug.Log("obj这个对象附带的标签为TestTag");
}
}
}
//游戏对象
private var obj : GameObject;
//渲染器
private var render : Renderer;
//贴图
public var texture : Texture;
function Start () {
//获取游戏对象
obj = GameObject.Find("Cube");
//给当前对象添加一个脚本组件
//obj.addComponent("Test");
//获取该对象的渲染器
render = obj.GetComponent("Renderer");
}
function OnGUI () {
if(GUILayout.Button("添加颜色",GUILayout.Width(100),GUILayout.Height(50))){
//修改渲染颜色为绿色
render.material.color = Color.green;
//为了避免残留,将贴图置空
render.material.mainTexture = null;
}
if(GUILayout.Button("添加贴图",GUILayout.Width(100),GUILayout.Height(50))){
//为了避免残留,将贴图置空
render.material = null;
//为了避免残留,将贴图置空
render.material.mainTexture = texture;
}
}
//球体对象
var obj : GameObject;
function Start () {
//获得球体对象
obj = GameObject.Find("Capsule");
}
function OnGUI () {
if(GUILayout.Button("开始克隆实例",GUILayout.Height(50))){
//克隆一个obj实例
var clone : GameObject = Instantiate(obj,obj.transform.position,obj.transform.rotation);
//5s后销毁该实例
Destroy(clone,5);
}
}
//立方体对象
var obj : GameObject;
function Start () {
//获得立方体对象
obj = GameObject.Find("Cube");
}
function OnGUI(){
if(GUILayout.Button("给立方体添加脚本组件",GUILayout.Height(50))){
//添加cube_script脚本
if(obj)
obj.AddComponent.();
//或UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(obj, "Assets/Script_04_07.js(13,25)", "cube_script");
}
if(GUILayout.Button("删除立方体脚本组件",GUILayout.Height(50))){
//删除立方体脚本组件
if(obj)
Destroy(obj.GetComponent("cube_script"));
}
if(GUILayout.Button("立即删除立方体对象",GUILayout.Height(50))){
//删除立方体对象
if(obj)
Destroy(obj);
}
if(GUILayout.Button("5s后删除立方体对象",GUILayout.Height(50))){
//5s后删除立方体对象
if(obj)
Destroy(obj,5);
}
}
function Update () {
}
cube_script.js
function Start () {
Debug.Log("脚本添加成功");
}
function OnDestroy () {
Debug.Log("脚本删除成功");
}
//立方体在x轴方向上的坐标
private var Value_X : float = 0.0f;
//立方体在y轴方向上的坐标
private var Value_Y : float = 0.0f;
//立方体在z轴方向上的坐标
private var Value_Z : float = 0.0f;
//立方体对象
private var obj : GameObject;
function Start () {
//得到立方体对象
obj = GameObject.Find("Cube");
}
function OnGUI () {
GUILayout.Box("移动立方体X轴");
Value_X = GUILayout.HorizontalSlider(Value_X,-10.0f,10.0f,GUILayout.Width(200));
GUILayout.Box("移动立方体y轴");
Value_Y = GUILayout.HorizontalSlider(Value_Y,-10.0f,10.0f,GUILayout.Width(200));
GUILayout.Box("移动立方体z轴");
Value_Z = GUILayout.HorizontalSlider(Value_Z,-10.0f,10.0f,GUILayout.Width(200));
//设置立方体的位置
obj.transform.position = Vector3(Value_X,Value_Y,Value_Z);
GUILayout.Label("立方体当前位置:"+obj.transform.position);
}
//立方体对象
private var objCube : GameObject;
//圆柱体对象
private var objCylinder : GameObject;
//旋转速度
private var speed : int = 100;
function Start () {
//获得对象
objCube = GameObject.Find("Cube");
objCylinder = GameObject.Find("Cylinder");
}
function OnGUI () {
if(GUILayout.Button("立方体沿x轴旋转",GUILayout.Height(50))){
objCube.transform.Rotate(Vector3.right ,Time.deltaTime * speed);
}
if(GUILayout.Button("立方体沿y轴旋转",GUILayout.Height(50))){
objCube.transform.Rotate(Vector3.up * Time.deltaTime * speed);
}
if(GUILayout.Button("立方体沿z轴旋转",GUILayout.Height(50))){
objCube.transform.Rotate(Vector3.forward * Time.deltaTime * speed);
}
if(GUILayout.Button("立方体围绕圆柱体旋转",GUILayout.Height(50))){
objCube.transform.RotateAround(objCylinder.transform.position,Vector3.up, Time.deltaTime * speed);
}
GUILayout.Label("立方体旋转角度:"+objCube.transform.rotation);
}
//立方体对象
var obj : GameObject;
function Start () {
//获得立方体对象
obj = GameObject.Find("Cube");
}
function OnGUI () {
if(GUILayout.Button("向前移动",GUILayout.Height(50))){
obj.transform.Translate(Vector3.forward * Time.deltaTime);
}
if(GUILayout.Button("向后移动",GUILayout.Height(50))){
obj.transform.Translate(-Vector3.forward * Time.deltaTime);
}
if(GUILayout.Button("向左移动",GUILayout.Height(50))){
obj.transform.Translate(Vector3.left * Time.deltaTime);
}
if(GUILayout.Button("向右移动",GUILayout.Height(50))){
obj.transform.Translate(Vector3.right * Time.deltaTime);
}
if(GUILayout.Button("向上移动",GUILayout.Height(50))){
obj.transform.Translate(Vector3.up * Time.deltaTime);
}
if(GUILayout.Button("向下移动",GUILayout.Height(50))){
obj.transform.Translate(Vector3.down * Time.deltaTime);
}
GUILayout.Label("立方体的位置:"+obj.transform.position);
}
var obj : GameObject;
//初始化缩放比例
var scaleX : float = 1.0;
var scaleY : float = 1.0;
var scaleZ : float = 1.0;
function Start () {
//得到缩放模型对象
obj = GameObject.Find("Cube");
}
function OnGUI () {
GUILayout.Label("x轴缩放");
scaleX = GUILayout.HorizontalSlider(scaleX,1.0,2.0,GUILayout.Width(100));
GUILayout.Label("y轴缩放");
scaleY = GUILayout.HorizontalSlider(scaleY,1.0,2.0,GUILayout.Width(100));
GUILayout.Label("z轴缩放");
scaleZ = GUILayout.HorizontalSlider(scaleZ,1.0,2.0,GUILayout.Width(100));
//重新计算缩放比例
obj.transform.localScale = Vector3(scaleX,scaleY,scaleZ);
}
注意JavaScript和C#的数据类型对应:
JS:int,float,boolean,String
C#:int,float,bool,string
JavaScript———–
Test0.js:
//整形
var i : int;
//浮点型
var f : float;
//布尔型
var b : boolean;
//字符串
var str : String;
//设置整形
function setInt(temp:int){
i = temp;
}
//设置浮点型
function setFloat(temp:float){
f = temp;
}
//设置布尔型
function setBoolean(temp:boolean){
b = temp;
}
//设置字符串
function setString(temp:String){
str = temp;
}
//获取整形
function getInt() : int{
return i;
}
//获取浮点形
function getFloat() : float{
return f;
}
//获取布尔型
function getBoolean() : boolean{
return b;
}
//获取字符串
function getString() : String{
return str;
}
Main.js:
//立方体对象
var obj : GameObject;
function Start () {
//获取立方体对象
obj = GameObject.Find("Cube");
//获取立方体绑定的脚本
var script : Test0 = obj.GetComponent("Test0");
//设置整形
script.setInt(100);
//设置浮点型
script.setFloat(10.0f);
//设置布尔型
script.setBoolean(true);
//设置字符串
script.setString("Test");
//获取信息并且打印
Debug.Log(script.getInt());
Debug.Log(script.getFloat());
Debug.Log(script.getBoolean());
Debug.Log(script.getString());
}
function Update () {
}
C#———–
Test1.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test1 : MonoBehaviour {
void Start () {}
//整形
int i;
//浮点型
float f;
//布尔型
bool b;
//字符串
string str;
//设置整形
public void setInt(int temp){
i = temp;
}
//设置浮点型
public void setFloat(float temp){
f = temp;
}
//设置布尔型
public void setBoolean(bool temp){
b = temp;
}
//设置字符串
public void setString(string temp){
str = temp;
}
//获取整形
public int getInt(){
return i;
}
//获取浮点形
public float getFloat(){
return f;
}
//获取布尔型
public bool getBoolean(){
return b;
}
//获取字符串
public string getString(){
return str;
}
}
Main.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour {
//立方体对象
GameObject obj;
Test1 script;
void Start () {
//获取立方体对象
obj = GameObject.Find("Cube");
//获取立方体绑定的脚本
script = obj.GetComponent();
//设置整形
script.setInt(100);
//设置浮点型
script.setFloat(10.0f);
//设置布尔型
script.setBoolean(true);
//设置字符串
script.setString("Test");
//获取信息并且打印
Debug.Log(script.getInt());
Debug.Log(script.getFloat());
Debug.Log(script.getBoolean());
Debug.Log(script.getString());
}
void Update () {
}
}
注意:Test0.js和Test1.cs是挂在Cube上得,而不是Camera上,否则会报类似于这种错误
NullReferenceException: Object reference not set to an instance of an object
function OnGUI(){
if(GUI.Button(Rect(100,50,200,100),"JavaScript调用C#")){
//获取C#脚本对象
var cs = this.GetComponent("CS_test");
//调用C#脚本中的方法
cs.CallMe("我来自JavaScript");
}
}
function CallMe(test : String){
Debug.Log(test);
}
CS_test.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CS_test : MonoBehaviour {
void OnGUI(){
if(GUI.Button(new Rect(100,170,200,100),"C#调用JavaScript")){
//获取JavaScript脚本对象
JS_test jsScript = (JS_test)GetComponent("JS_test");
//调用JavaScript脚本中的方法
jsScript.CallMe("我来自C#");
}
}
void CallMe(string test){
Debug.Log(test);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_04_13 : MonoBehaviour {
// Use this for initialization
void OnGUI(){
GUILayout.Label ("当前游戏时间:"+Time.time);
GUILayout.Label ("上一帧所消耗的时间:"+Time.deltaTime);
GUILayout.Label ("固定增量时间:" + Time.fixedTime);
GUILayout.Label ("上一帧所消耗的固定时间:"+Time.fixedDeltaTime);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_04_14 : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
Debug.Log ("开始等待:"+Time.time);
yield return new WaitForSeconds (2);
Debug.Log ("结束等待:"+Time.time);
}
/*
* 或
IEnumerator Start () {
return Test ();
}
IEnumerator Test(){
Debug.Log ("开始等待:"+Time.time);
yield return new WaitForSeconds (2);
Debug.Log ("结束等待:"+Time.time);
}
*/
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_03_15 : MonoBehaviour {
// Use this for initialization
void Start () {
int a = Random.Range(0,100);
float b = Random.Range(0.0f,10.0f);
Debug.Log ("获取一个0-100之间的整型随机数:"+a);
Debug.Log ("获取一个0.0f-10.0f之间的浮点型随机数:"+b);
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_04_16 : MonoBehaviour {
//是否开始插值旋转
bool isRotation = false;
void OnGUI () {
if(GUILayout.Button("旋转固定角度",GUILayout.Height(50))){
gameObject.transform.rotation = Quaternion.Euler (0.0f,50.0f,0.0f);
}
if(GUILayout.Button("插值旋转固定角度",GUILayout.Height(50))){
isRotation = true;
}
}
// Update is called once per frame
void Update () {
//开始插值旋转
if(isRotation){
gameObject.transform.rotation = Quaternion.Slerp
(gameObject.transform.rotation,
Quaternion.Euler (0.0f,50.0f,0.0f),
Time.time*0.1f);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_04_17 : MonoBehaviour {
//大地图地形对象
GameObject plane;
//大地图主角对象
GameObject cube;
//大地图的宽度
float mapWidth;
//大地图的高度
float mapHeight;
//地图边界的监测数值
float widthCheck;
float heightCheck;
//小地图主角的位置
float mapcube_x = 0;
float mapcube_y = 0;
//GUI按钮是否被按下
bool keyUp;
bool keyDown;
bool keyLeft;
bool keyRight;
//小地图的背景贴图
public Texture map;
//小地图的主角贴图
public Texture map_cube;
// Use this for initialization
void Start () {
//得到大地图对象
plane = GameObject.Find("Plane");
//得到大地图主角对象
cube = GameObject.Find("Cube");
//得到大地图默认宽度
float size_x = plane.GetComponent().mesh.bounds.size.x;
//得到大地图宽度的缩放比例
float scal_x = plane.transform.localScale.x;
//得到大地图默认高度
float size_z = plane.GetComponent().mesh.bounds.size.z;
//得到大地图高度的缩放比例
float scal_z = plane.transform.localScale.z;
//将原始宽度乘以缩放比例,计算其真实宽度
mapWidth = size_x * scal_x;
mapHeight = size_z * scal_z;
//越界监测的宽度
widthCheck = mapWidth / 2;
heightCheck = mapHeight / 2;
check();
}
void OnGUI () {
keyUp = GUILayout.RepeatButton ("向前移动");
keyDown = GUILayout.RepeatButton ("向后移动");
keyLeft = GUILayout.RepeatButton ("向左移动");
keyRight = GUILayout.RepeatButton ("向右移动");
//绘制小地图背景
GUI.DrawTexture(new Rect(Screen.width-map.width,0,map.width,map.height),map);
//绘制小地图上的主角
GUI.DrawTexture(new Rect(mapcube_x,mapcube_y,map_cube.width,map_cube.height),map_cube);
}
void FixedUpdate(){
if(keyUp){
//向前移动
cube.transform.Translate(Vector3.forward * Time.deltaTime * 5);
check();
}
if(keyDown){
//向后移动
cube.transform.Translate(-Vector3.forward * Time.deltaTime * 5);
check();
}
if(keyLeft){
//向左移动
cube.transform.Translate(-Vector3.right * Time.deltaTime * 5);
check();
}
if(keyRight){
//向右移动
cube.transform.Translate(Vector3.right * Time.deltaTime * 5);
check();
}
}
//越界监测
void check(){
//得到当前主角在地图中的坐标
float x = cube.transform.position.x;
float z = cube.transform.position.z;
//当主角超过地图范围时,重新计算主角坐标
if(x >= widthCheck){
x = widthCheck;
}
if(x <= -widthCheck){
x = -widthCheck;
}
if(z >= heightCheck){
z = heightCheck;
}
if(z <= -heightCheck){
z = -heightCheck;
}
cube.transform.position = new Vector3 (x,cube.transform.position.y,z);
//根据比例计算小地图中"主角"的坐标
mapcube_x = (map.width/mapWidth * x) + ((map.width/2)-(map_cube.width/2))+
(Screen.width-map.width);
mapcube_y = map.height - ((map.height/mapHeight * z) + (map.height / 2));
}
}
导入地形资源:在Project视图中点击鼠标右键,选择“Import Package”-“Custom Package…”
在3D世界中,所有游戏元素都置身于天空盒子当中。天空盒子资源包可直接导入。
在“Projection”下拉列表中选择“Perspective”后摄像机的角度呈放射性观察。
在“Projection”下拉列表中选择“Orthographic”后摄像机的角度呈垂直性观察。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_05_02 : MonoBehaviour {
private Camera camera;
// Use this for initialization
void Start () {
//获取摄像机组件
camera = gameObject.GetComponent();
}
// Update is called once per frame
void OnGUI () {
if(GUILayout.Button("放射观察",GUILayout.Height(50))){
camera.orthographic = false;
}
if(GUILayout.Button("垂直观察",GUILayout.Height(50))){
camera.orthographic = true;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine;
public class Script_05_03 : MonoBehaviour {
[MenuItem("新的菜单栏/克隆选择的对象")]
static void ClothObject(){
Instantiate (Selection.activeTransform,Vector3.zero,Quaternion.identity);
}
[MenuItem("新的菜单栏/克隆选择的对象",true)]
static bool NoClothObject(){
return Selection.activeGameObject != null;
}
[MenuItem("新的菜单栏/删除选择的对象")]
static void RemoveObject(){
DestroyImmediate (Selection.activeGameObject,true);
}
[MenuItem("新的菜单栏/删除选择的对象",true)]
static bool NoRemoveObject(){
return Selection.activeGameObject != null;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine;
//添加该脚本至"Component"菜单项中
[AddComponentMenu("新的脚本/自动选转")]
public class Script_03_04 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//自身旋转
transform.Rotate(0.0f,Time.deltaTime*200,0.0f);
}
}
private var Camera0 : GameObject;
private var Camera1 : GameObject;
private var Camera2 : GameObject;
function Start () {
//获取摄像机对象
Camera0 = GameObject.Find("Camera0");
Camera1 = GameObject.Find("Camera1");
Camera2 = GameObject.Find("Camera2");
}
function OnGUI () {
if(GUILayout.Button("投射侧面",GUILayout.Height(50))){
//关闭Camera1和Camera2
Camera1.active = false;
Camera2.active = false;
//打开Camera0
Camera0.active = true;
}
if(GUILayout.Button("投射正面",GUILayout.Height(50))){
//关闭Camera0和Camera2
Camera0.active = false;
Camera2.active = false;
//打开Camera1
Camera1.active = true;
}
if(GUILayout.Button("投射上面",GUILayout.Height(50))){
//关闭Camera0和Camera1
Camera0.active = false;
Camera1.active = false;
//打开Camera2
Camera2.active = true;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_02 : MonoBehaviour {
//施加普通力的对象
GameObject addFrceObj = null;
//施加目标位置力的对象
GameObject addPosObj = null;
//目标对象
GameObject cubeObj = null;
// Use this for initialization
void Start () {
//获取施加普通力的对象
addFrceObj = GameObject.Find("Sphere0");
//获取施加位置力的对象
addPosObj = GameObject.Find("Sphere1");
//获取目标象
cubeObj = GameObject.Find("Cube");
}
void OnGUI () {
if(GUILayout.Button("普通力",GUILayout.Height(50))){
//施加一个力,x轴方向力的大小为1000,y轴方向力的大小为1000
addFrceObj.GetComponent().AddForce(1000,0,1000);
}
if(GUILayout.Button("位置力",GUILayout.Height(50))){
//施加一个位置力,物体将会向这个位置移动,力的模式为冲击力
Vector3 force = cubeObj.transform.position-addPosObj.transform.position;
addPosObj.GetComponent().AddForceAtPosition(force,addPosObj.transform.position,ForceMode.Impulse);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollisionTest : MonoBehaviour {
//碰撞显示信息
string show = null;
// Use this for initialization
void Start () {
//默认显示内容
show = "未发生碰撞";
}
//进入碰撞
void OnCollisionEnter(Collision collision){
show = "进入碰撞,碰撞名称:"+collision.gameObject.name;
}
//碰撞中
void OnCollisionStay(Collision collision){
show = "碰撞中,碰撞名称:"+collision.gameObject.name;
}
//碰撞结束
void OnCollisionExit(Collision collision){
show = "碰撞结束,碰撞名称:"+collision.gameObject.name;
//碰撞结束后让物体休眠
collision.gameObject.GetComponent().Sleep();
}
// Update is called once per frame
void OnGUI () {
//将碰撞信息显示出来
GUI.Label(new Rect(100,0,300,40),show);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_05 : MonoBehaviour {
//角色控制器对象
private CharacterController controller = null;
//角色移动的速度
private float moveSpeed = 30.0f;
//角色旋转的速度
private float rotateSpeed = 3.0f;
// Use this for initialization
void Start () {
//获取角色控制器对象
controller = GetComponent();
}
// Update is called once per frame
void OnGUI () {
//控制角色旋转
if(GUILayout.RepeatButton("向左旋转")){
transform.Rotate (0,-rotateSpeed,0);
}
if(GUILayout.RepeatButton("向右旋转")){
transform.Rotate (0,rotateSpeed,0);
}
//控制角色移动
if(GUILayout.RepeatButton("向前移动")){
controller.SimpleMove (Vector3.forward*moveSpeed);
}
if(GUILayout.RepeatButton("向后移动")){
controller.SimpleMove (-Vector3.forward*moveSpeed);
}
if(GUILayout.RepeatButton("向左移动")){
controller.SimpleMove (-Vector3.right*moveSpeed);
}
if(GUILayout.RepeatButton("向右移动")){
controller.SimpleMove (Vector3.right*moveSpeed);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_06 : MonoBehaviour {
//角色控制器对象
private CharacterController controller = null;
//角色移动速度
private float moveSpeed = 3.0f;
//角色旋转的速度
private float rotateSpeed = 3.0f;
// Use this for initialization
void Start () {
//获取角色控制器对象
controller = GetComponent();
}
// Update is called once per frame
void OnGUI () {
//控制角色旋转
if(GUILayout.RepeatButton("向左旋转")){
transform.Rotate (0,-rotateSpeed,0);
}
if(GUILayout.RepeatButton("向右旋转")){
transform.Rotate (0,rotateSpeed,0);
}
//控制角色移动
if(GUILayout.RepeatButton("向前移动")){
Vector3 forward = transform.TransformDirection (Vector3.forward);
controller.Move (forward*moveSpeed);
}
if(GUILayout.RepeatButton("向后移动")){
Vector3 forward = transform.TransformDirection (Vector3.forward);
controller.Move (forward*-moveSpeed);
}
if(GUILayout.RepeatButton("向左移动")){
Vector3 right = transform.TransformDirection (Vector3.right);
controller.Move (right*-moveSpeed);
}
if(GUILayout.RepeatButton("向右移动")){
Vector3 right = transform.TransformDirection (Vector3.right);
controller.Move (right*moveSpeed);
}
//控制角色飞行与降落
if(GUILayout.RepeatButton("起飞")){
transform.Translate (0,1,0);
}
if(GUILayout.RepeatButton("降落")){
transform.Translate (0,-1,0);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_07 : MonoBehaviour {
//角色控制器对象
private CharacterController controller = null;
//角色移动速度
private float moveSpeed = 0.3f;
//角色旋转的速度
private float rotateSpeed = 0.3f;
//碰撞的游戏对象
private GameObject colliderObj = null;
// Use this for initialization
void Start () {
//获取角色控制器对象
controller = GetComponent();
}
// Update is called once per frame
void OnGUI () {
//控制角色旋转
if(GUILayout.RepeatButton("向左旋转")){
transform.Rotate (0,-rotateSpeed,0);
}
if(GUILayout.RepeatButton("向右旋转")){
transform.Rotate (0,rotateSpeed,0);
}
//控制角色移动
if(GUILayout.RepeatButton("向前移动")){
Vector3 forward = transform.TransformDirection (Vector3.forward);
controller.Move (forward*moveSpeed);
}
if(GUILayout.RepeatButton("向后移动")){
Vector3 forward = transform.TransformDirection (Vector3.forward);
controller.Move (forward*-moveSpeed);
}
if(GUILayout.RepeatButton("向左移动")){
Vector3 right = transform.TransformDirection (Vector3.right);
controller.Move (right*-moveSpeed);
}
if(GUILayout.RepeatButton("向右移动")){
Vector3 right = transform.TransformDirection (Vector3.right);
controller.Move (right*moveSpeed);
}
//控制角色飞行与降落
if(GUILayout.RepeatButton("起飞")){
transform.Translate (0,1,0);
}
if(GUILayout.RepeatButton("降落")){
transform.Translate (0,-1,0);
}
//碰撞中
if(controller.collisionFlags == CollisionFlags.Sides){
if(colliderObj!=null){
GUI.color = Color.black;
GUI.Label (new Rect(200,100,200,100),"碰撞的游戏对象为:"+
colliderObj.name);
}
}
}
void OnControllerColliderHit(ControllerColliderHit hit){
//得到碰撞的游戏对象
colliderObj = hit.gameObject;
}
}
创建一条射线时,首先需要知道射线的起点和终点在3D世界坐标系中的坐标。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_08 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//创建射线,从零点发射到对象
Ray ray = new Ray(Vector3.zero,transform.position);
//计算射线的起点和终点
RaycastHit hit;
Physics.Raycast (ray,out hit,100);
//使用调试方法绘制这条线(调试方法仅在Scene视图中存在)
Debug.DrawLine(ray.origin,hit.point);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_09 : MonoBehaviour {
//靶心贴图
public Texture texture;
//提示信息
private string info;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//创建从摄像机到鼠标之间的射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//判断该射线是否打中游戏对象
if (Physics.Raycast (ray, out hit)) {
info = "打中靶心";
} else {
info = "未打中靶心";
}
}
void OnGUI(){
//计算准心贴图的坐标
Rect rect = new Rect(Input.mousePosition.x-(texture.width>>1),
Screen.height-Input.mousePosition.y-(texture.height>>1),
texture.width,
texture.height);
//绘制准心贴图
GUI.DrawTexture(rect,texture);
//输入打靶子的信息
GUILayout.Label(info+",打中的坐标为:"+Input.mousePosition);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_10 : MonoBehaviour {
//链条关节游戏对象
GameObject connectedObj = null;
//当前链条关节组件
Component jointComponent = null;
// Use this for initialization
void Start () {
//获取链条关节的游戏对象
connectedObj = GameObject.Find("Cube1");
}
// Update is called once per frame
void OnGUI () {
if(GUILayout.Button("添加链条关节")){
ResetJoint ();
jointComponent = gameObject.AddComponent ();
HingeJoint hJoint = (HingeJoint)jointComponent;
connectedObj.GetComponent().useGravity = true;
hJoint.connectedBody = connectedObj.GetComponent();
}
if(GUILayout.Button("添加固定关节")){
ResetJoint ();
jointComponent = gameObject.AddComponent ();
FixedJoint fJoint = (FixedJoint)jointComponent;
connectedObj.GetComponent().useGravity = true;
fJoint.connectedBody = connectedObj.GetComponent();
}
if(GUILayout.Button("添加弹簧关节")){
ResetJoint ();
jointComponent = gameObject.AddComponent ();
SpringJoint sJoint = (SpringJoint)jointComponent;
connectedObj.GetComponent().useGravity = true;
sJoint.connectedBody = connectedObj.GetComponent();
}
if(GUILayout.Button("添加角色关节")){
ResetJoint ();
jointComponent = gameObject.AddComponent ();
CharacterJoint cJoint = (CharacterJoint)jointComponent;
connectedObj.GetComponent().useGravity = true;
cJoint.connectedBody = connectedObj.GetComponent();
}
if(GUILayout.Button("添加可配置关节")){
ResetJoint ();
jointComponent = gameObject.AddComponent ();
ConfigurableJoint coJoint = (ConfigurableJoint)jointComponent;
connectedObj.GetComponent().useGravity = true;
coJoint.connectedBody = connectedObj.GetComponent();
}
}
//重置关节
void ResetJoint(){
//销毁之前添加的关节组件
Destroy(jointComponent);
//重置对象位置
this.transform.position = new Vector3(821.0f,72.0f,660.0f);
connectedObj.gameObject.transform.position = new Vector3 (805.0f,48.0f,660.0f);
//不感应重力
connectedObj.GetComponent().useGravity = false;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_11 : MonoBehaviour {
//粒子对象
GameObject particle = null;
//粒子在x轴方向的速度
float velocity_x = 0.0f;
//粒子在y轴方向的速度
float velocity_y = 0.0f;
//粒子在z轴方向的速度
float velocity_z = 0.0f;
// Use this for initialization
void Start () {
//获得粒子对象
particle = GameObject.Find("ParticleSystem");
}
// Update is called once per frame
void OnGUI () {
//通过拖动设置粒子的最大尺寸
GUILayout.Label("粒子最大尺寸");
particle.GetComponent().maxSize = GUILayout.HorizontalSlider
(particle.GetComponent().maxSize,0.0f,10.0f,GUILayout.Width(150));
//通过拖动设置粒子的最大消失时间
GUILayout.Label("粒子消失时间");
particle.GetComponent().maxEnergy = GUILayout.HorizontalSlider
(particle.GetComponent().maxEnergy,0.0f,10.0f,GUILayout.Width(150));
//通过拖动设置粒子的最大生成数量
GUILayout.Label("粒子的最大生成数量");
particle.GetComponent().maxEmission = GUILayout.HorizontalSlider
(particle.GetComponent().maxEmission,0.0f,10.0f,GUILayout.Width(150));
//通过拖动设置粒子x轴的移动速度
GUILayout.Label("粒子x轴的移动速度");
velocity_x = GUILayout.HorizontalSlider (velocity_x,0.0f,10.0f,GUILayout.Width(150));
particle.GetComponent().worldVelocity = new Vector3(velocity_x,
particle.GetComponent().worldVelocity.y,particle.GetComponent().worldVelocity.z);
//通过拖动设置粒子y轴的移动速度
GUILayout.Label("粒子y轴的移动速度");
velocity_y = GUILayout.HorizontalSlider (velocity_y,0.0f,10.0f,GUILayout.Width(150));
particle.GetComponent().worldVelocity = new Vector3(particle.GetComponent().worldVelocity.x,
velocity_y,particle.GetComponent().worldVelocity.z);
//通过拖动设置粒子z轴的移动速度
GUILayout.Label("粒子z轴的移动速度");
velocity_z = GUILayout.HorizontalSlider (velocity_z,0.0f,10.0f,GUILayout.Width(150));
particle.GetComponent().worldVelocity = new Vector3(particle.GetComponent().worldVelocity.x,
particle.GetComponent().worldVelocity.y,velocity_z);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_12 : MonoBehaviour {
//布料对象
Cloth cloth = null;
// Use this for initialization
void Start () {
//获取布料对象
cloth = (Cloth)GetComponent();
}
// Update is called once per frame
void OnGUI () {
//移动布料
if(GUILayout.RepeatButton("向上")){
cloth.externalAcceleration = new Vector3 (0,1,0);
}
if(GUILayout.RepeatButton("向下")){
cloth.externalAcceleration = new Vector3 (0,-1,0);
}
if(GUILayout.RepeatButton("向左")){
cloth.externalAcceleration = new Vector3 (1,0,0);
}
if(GUILayout.RepeatButton("向右")){
cloth.externalAcceleration = new Vector3 (-1,0,0);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_13 : MonoBehaviour {
//路径渲染对象
private TrailRenderer trailRender;
// Use this for initialization
void Start () {
//获取路径渲染对象
trailRender = gameObject.GetComponent();
}
// Update is called once per frame
void OnGUI () {
if(GUILayout.Button("增加宽度",GUILayout.Height(50))){
trailRender.startWidth += 1;
trailRender.endWidth += 1;
}
if(GUILayout.Button("显示路径",GUILayout.Height(50))){
trailRender.enabled = true;
}
if(GUILayout.Button("隐藏路径",GUILayout.Height(50))){
trailRender.enabled = false;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_06_14 : MonoBehaviour {
//炮弹对象
private GameObject obj;
//准心贴图
public Texture texture;
// Use this for initialization
void Start () {
//获取炮弹对象
obj = GameObject.Find("Sphere0");
//隐藏默认鼠标图标
Cursor.visible = false;
}
// Update is called once per frame
void FixedUpdate () {
//点击鼠标左键后
if(Input.GetMouseButton(0)){
//创建从摄像机发射到鼠标位置的射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//判断射线是否与游戏对象相交
if(Physics.Raycast(ray,out hit)){
//确保游戏对象为围墙
if(hit.collider.name == "Cube"){
//计算炮弹与目标点之间的距离
Vector3 direction = hit.transform.position - obj.transform.position;
//发射炮弹
obj.GetComponent().AddForceAtPosition(direction,hit.transform.position,ForceMode.Impulse);
}
}
}
}
void OnGUI(){
//绘制准心
Rect rect = new Rect(Input.mousePosition.x - (texture.width>>1),
Screen.height - Input.mousePosition.y - (texture.height>>1),
texture.width,
texture.height);
GUI.DrawTexture (rect,texture);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_01 : MonoBehaviour {
//记录某按键按下的帧数
int keyFrame = 0;
// Use this for initialization
void Start () {
Debug.Log ("你好");
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.W)){
Debug.Log ("您按下了W键");
}
if(Input.GetKeyUp(KeyCode.S)){
Debug.Log ("您抬起了S键");
}
if(Input.GetKey(KeyCode.A)){
//记录按下的帧数
keyFrame++;
Debug.Log ("A连按:"+keyFrame+"帧");
}
if(Input.GetKeyUp(KeyCode.A)){
//抬起后清空帧数
keyFrame=0;
}
/*
if(Input.anyKey){
Debug.Log ("任意按键被按下");
}
*/
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_05 : MonoBehaviour {
//方向键"上"的贴图
public Texture imageUp;
//方向键"下"的贴图
public Texture imageDown;
//方向键"左"的贴图
public Texture imageLeft;
//方向键"右"的贴图
public Texture imageRight;
//按键成功的贴图
public Texture imageSuccess;
//自定义方向键的存储值
public const int KEY_UP = 0;
public const int KEY_DOWN = 1;
public const int KEY_LEFT = 2;
public const int KEY_RIGHT = 3;
public const int KEY_FIRT = 4;
//连续按键的时间限制
public const int FRAME_COUNT = 100;
//仓库中存储技能的数量
public const int SAMPLE_SIZE = 3;
//每组技能的按键数量
public const int SAMPLE_COUNT = 5;
//技能仓库
int[,] Sample =
{
//下+前+下+前+拳
{KEY_DOWN,KEY_RIGHT,KEY_DOWN,KEY_RIGHT,KEY_FIRT},
//下+前+下+后+拳
{KEY_DOWN,KEY_RIGHT,KEY_DOWN,KEY_LEFT,KEY_FIRT},
//下+后+下+后+拳
{KEY_DOWN,KEY_LEFT,KEY_DOWN,KEY_LEFT,KEY_FIRT},
};
//记录当前按下按键的键值
int currentkeyCode = 0;
//是否开启监听按键
bool startFrame = false;
//记录当前监听的时间
int currentFrame = 0;
//保存一段时间内玩家输入的按键组合
List<int> playerSample;
//标志是否完成按键操作
bool isSuccess = false;
// Use this for initialization
void Start () {
//初始化按键组合链表
playerSample = new List<int>();
}
// Update is called once per frame
void OnGUI () {
//获得按键组合链表中存储按键的数量
int size = playerSample.Count;
//遍历该按键组合链表
for(int i = 0;i//将按下按键对应的图片显示在屏幕中
int key = playerSample[i];
Texture temp = null;
switch(key){
case KEY_UP:
temp = imageUp;
break;
case KEY_DOWN:
temp = imageDown;
break;
case KEY_LEFT:
temp = imageLeft;
break;
case KEY_RIGHT:
temp = imageRight;
break;
}
if(temp != null){
GUILayout.Label (temp);
}
}
if(isSuccess){
//显示成功贴图
GUILayout.Label(imageSuccess);
}
//默认提示信息
GUILayout.Label("连续组合按键1:下、前、下、前、拳");
GUILayout.Label("连续组合按键2:下、前、下、后、拳");
GUILayout.Label("连续组合按键3:下、后、下、前、拳");
}
void Update(){
//更新按键
UpdateKey();
if(Input.anyKeyDown){
if(isSuccess){
//按键成功后重置
isSuccess = false;
Reset ();
}
if(!startFrame){
//启动时间计数器
startFrame = true;
}
//将按键值添加到链表中
playerSample.Add(currentkeyCode);
//遍历列表
int size = playerSample.Count;
if(size == SAMPLE_COUNT){
for(int i = 0;iint SuccessCount = 0;
for(int j = 0;jint temp = playerSample [j];
if(temp==Sample[i,j]){
SuccessCount++;
}
}
//玩家按下的组合按键与仓库中的按键组合相同,表示成功释放技能
if(SuccessCount==SAMPLE_COUNT){
isSuccess = true;
break;
}
}
}
}
if(startFrame){
//递增计数器
currentFrame++;
}
if(currentFrame>=FRAME_COUNT){
//计数器超时
if(!isSuccess){
Reset();
}
}
}
void Reset(){
//重置按键相关信息
currentFrame = 0;
startFrame = false;
playerSample.Clear();
}
void UpdateKey(){
//获取当前键盘的按键信息
if(Input.GetKeyDown(KeyCode.W)){
currentkeyCode = KEY_UP;
}
if(Input.GetKeyDown(KeyCode.S)){
currentkeyCode = KEY_DOWN;
}
if(Input.GetKeyDown(KeyCode.A)){
currentkeyCode = KEY_LEFT;
}
if(Input.GetKeyDown(KeyCode.D)){
currentkeyCode = KEY_RIGHT;
}
if(Input.GetKeyDown(KeyCode.Space)){
currentkeyCode = KEY_FIRT;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_06 : MonoBehaviour {
//鼠标长按帧数
int MouseFrame = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
Debug.Log ("点击鼠标左键的位置为:"+Input.mousePosition);
}
if(Input.GetMouseButtonUp(1)){
Debug.Log ("抬起鼠标右键的位置为:"+Input.mousePosition);
}
if(Input.GetMouseButtonDown(2)){
Debug.Log ("点击鼠标中键的位置为:"+Input.mousePosition);
}
if(Input.GetMouseButton(2)){
MouseFrame++;
Debug.Log ("鼠标中键长按"+MouseFrame+"帧");
}
if(Input.GetMouseButtonUp(2)){
MouseFrame = 0;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_09 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("test")){
Debug.Log ("单次按下test自定义按键");
}
if(Input.GetButton("test")){
Debug.Log ("长按test自定义按键");
}
if(Input.GetButtonUp("test")){
Debug.Log ("抬起test自定义按键");
}
}
}
按键轴的数值默认为0,按下某个轴上两遍的按钮时,其值分别是“1”与“-1”。Negative为-1,Positive为1。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_10 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float value = Input.GetAxis ("test");
Debug.Log ("按键轴的数值为:"+value);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_15 : MonoBehaviour {
//绘制线段的材质
public Material material;
//此绘制方法由系统调用
void OnPostRender(){
if(!material){
Debug.LogError ("请给材质资源赋值");
return;
}
//设置该材质通道,0为默认值
material.SetPass(0);
//设置绘制2D图像
GL.LoadOrtho();
//表示开始绘制,绘制类型为线段
GL.Begin(GL.LINES);
//绘制线段0
DrawLine(0,0,200,100);
//绘制线段1
DrawLine(0,50,200,150);
//绘制线段2
DrawLine(0,100,200,200);
//结束绘制
GL.End();
}
void DrawLine(float x1,float y1,float x2,float y2){
//绘制线段,需要将屏幕中的某个点的像素坐标除以屏幕宽或高
GL.Vertex(new Vector3(x1/Screen.width,y1/Screen.height,0));
GL.Vertex(new Vector3(x2/Screen.width,y2/Screen.height,0));
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_16 : MonoBehaviour {
//绘制线段材质
public Material material;
private List lineInfo;
// Use this for initialization
void Start () {
//初始化鼠标线段链表
lineInfo = new List();
}
// Update is called once per frame
void Update () {
//将每次鼠标改变的位置存储进链表
lineInfo.Add(Input.mousePosition);
}
void OnGUI(){
GUILayout.Label ("当前鼠标x轴位置:"+Input.mousePosition.x);
GUILayout.Label ("当前鼠标y轴位置:"+Input.mousePosition.y);
}
//此绘制方法由系统调用
void OnPostRender(){
if(!material){
Debug.LogError ("请给材质资源赋值");
return;
}
//设置该材质通道,0为默认值
material.SetPass(0);
//设置绘制2D图像
GL.LoadOrtho();
//表示开始绘制,绘制类型为线段
GL.Begin(GL.LINES);
//得到鼠标垫信息的总数量
int size = lineInfo.Count;
//遍历鼠标点的链表
for(int i = 0;i1;i++){
Vector3 start = lineInfo [i];
Vector3 end = lineInfo[i+1];
//绘制线段
DrawLine(start.x,start.y,end.x,end.y);
}
//结束绘制
GL.End();
}
void DrawLine(float x1,float y1,float x2,float y2){
//绘制线段,需要将屏幕中的某个点的像素坐标除以屏幕宽或高
GL.Vertex(new Vector3(x1/Screen.width,y1/Screen.height,0));
GL.Vertex(new Vector3(x2/Screen.width,y2/Screen.height,0));
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_17 : MonoBehaviour {
//可用材质
public Material mat0;
public Material mat1;
public Material mat3;
void OnPostRender(){
//绘制正四边形
DrawRect(100,100,100,100,mat0);
DrawRect(100,100,100,100,mat1);
//绘制无规则四边形
DrawQuads(15,5,10,115,95,110,90,10,mat3);
}
/*
* 绘制正四边形
* x : x轴起始坐标
* y : y轴起始坐标
* width : 正四边形的宽
* height : 正四边形的高
*/
void DrawRect(float x,float y,float width,float height,Material mat){
GL.PushMatrix ();
mat0.SetPass (0);
GL.LoadOrtho ();
//绘制类型为四边形
GL.Begin(GL.QUADS);
GL.Vertex3 (x/Screen.width,y/Screen.height,0);
GL.Vertex3 (x/Screen.width,(y+height)/Screen.height,0);
GL.Vertex3 ((x+width)/Screen.width,(y+height)/Screen.height,0);
GL.Vertex3 ((x+width)/Screen.width,y/Screen.height,0);
GL.End ();
GL.PopMatrix ();
}
/*
* 绘制无规则的四边形
* x1 : 起始点1的横坐标
* y1 : 起始点1的纵坐标
* x2 : 起始点2的横坐标
* y2 : 起始点2的纵坐标
* x3 : 起始点3的横坐标
* y3 : 起始点3的纵坐标
* x4 : 起始点4的横坐标
* y4 : 起始点4的纵坐标
*/
void DrawQuads(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4,Material mat){
GL.PushMatrix ();
mat.SetPass (0);
GL.LoadOrtho ();
//绘制类型为四边形
GL.Begin(GL.QUADS);
GL.Vertex3 (x1/Screen.width,y1/Screen.height,0);
GL.Vertex3 (x2/Screen.width,y2/Screen.height,0);
GL.Vertex3 (x3/Screen.width,y3/Screen.height,0);
GL.Vertex3 (x4/Screen.width,y4/Screen.height,0);
GL.End ();
GL.PopMatrix ();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_07_18 : MonoBehaviour {
//材质
public Material mat;
void OnPostRender(){
//绘制三角形
DrawTriangle(100,0,100,200,200,100,mat);
}
void DrawTriangle(float x1,float y1,float x2,float y2,float x3,float y3,Material mat){
mat.SetPass (0);
GL.LoadOrtho ();
//绘制三角形
GL.Begin(GL.TRIANGLES);
GL.Vertex3 (x1/Screen.width,y1/Screen.height,0);
GL.Vertex3 (x2/Screen.width,y2/Screen.height,0);
GL.Vertex3 (x3/Screen.width,y3/Screen.height,0);
GL.End ();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Script_08_01 : MonoBehaviour {
//用户姓名
private string username = "";
//用户号码
private string usernumber = "";
//用户年龄
private string userage = "";
//用户身高
private string userheight = "";
//是否将信息显示
private bool showInfo = false;
// Use this for initialization
void Start () {
}
void OnGUI(){
GUILayout.BeginHorizontal ("box",GUILayout.Width(200));
GUILayout.Label ("请输入姓名");
username = GUILayout.TextField (username,10);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal ("box");
GUILayout.Label ("请输入号码");
usernumber = GUILayout.TextField (usernumber,10);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal ("box");
GUILayout.Label ("请输年龄");
userage = GUILayout.TextField (userage,10);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal ("box");
GUILayout.Label ("请输身高");
userheight = GUILayout.TextField (userheight,10);
GUILayout.EndHorizontal();
if(GUILayout.Button("提交数据")){
showInfo = true;
//持久化保存数据
PlayerPrefs.SetString("username",username);
PlayerPrefs.SetString("usernumber",usernumber);
PlayerPrefs.SetInt("userage",int.Parse(userage));
PlayerPrefs.SetFloat("username",float.Parse(userheight));
}
if(GUILayout.Button("取消查看")){
showInfo = false;
//删除所有持久化对应值
PlayerPrefs.DeleteAll();
}
if(showInfo){
//将信息显示出来,如果找不到对应的值则显示信息默认值
GUILayout.Label("输入的姓名为:"+PlayerPrefs.GetString("username","姓名默认值"));
GUILayout.Label("输入的号码为:"+PlayerPrefs.GetString("usernumber","号码默认值"));
GUILayout.Label("输入的年龄为:"+PlayerPrefs.GetInt("userage",0).ToString());
GUILayout.Label("输入的身高为:"+PlayerPrefs.GetFloat("userheight",0.0f).ToString());
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Script_08_02 : MonoBehaviour {
// Use this for initialization
void Start () {
//创建文件,共写入3次数据
CreateFile(Application.dataPath,"FileName","TestInfo0");
CreateFile(Application.dataPath,"FileName","TestInfo1");
CreateFile(Application.dataPath,"FileName","TestInfo2");
}
// Update is called once per frame
void Update () {
}
void CreateFile(string path,string name,string info){
//文件流信息
StreamWriter sw;
FileInfo t = new FileInfo (path+"//"+name);
if (!t.Exists) {
sw = t.CreateText ();
} else {
//如果存在,则打开文件
sw = t.AppendText();
}
//以行的形式写入信息
sw.WriteLine(info);
//关闭流
sw.Close();
//销毁流
sw.Dispose();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class Script_08_03 : MonoBehaviour {
// Use this for initialization
void Start () {
//读取文件
ArrayList info = LoadFile(Application.dataPath,"FileName");
//遍历文本信息,将其打印出来
foreach(string str in info){
Debug.Log (str);
}
}
// Update is called once per frame
void Update () {
}
ArrayList LoadFile(string path,string name){
//使用流读取
StreamReader sr = null;
try{
sr = File.OpenText(path+"//"+name);
}catch(Exception e){
//通过路径与名称均为找到文件,则直接返回空
return null;
}
string line;
ArrayList arrList = new ArrayList ();
while((line = sr.ReadLine())!=null){
//逐行读取
//将每一行的内容存入数组链表容器中
arrList.Add(line);
}
//关闭流
sr.Close();
//销毁流
sr.Dispose();
//返回数组链表容器
return arrList;
}
}