1.作为行为组件的脚本:Unity 中的脚本是什么?了解作为 Unity 脚本的行为组件,以及如何创建这些脚本并将它们附加到对象。
脚本相当于unity中的行为组件。与其他组件一样,脚本也可以应用于对象,并显示在inspector(检查器)中,
创建脚本并附加的方法:
1.项目面板中,右键创建,c#脚本,通过拖拽的方式,关联到相应的对象。
2.inspector面板中添加组件,然后选新脚本(new script)
3.顶部菜单,组件,脚本。
实例,输入rgb改变方块颜色,需要用到mesh renderer组件
using UnityEngine;
using System.Collections;
public class ExampleBehaviourScript : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
GetComponent<Renderer> ().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue;
}
}
}
2.变量和函数:什么是变量和函数?它们如何为我们存储和处理信息?
变量
蛮简单的,和c一样,比如,int x = 5;其中,等号前半部分是声明,后半部分是初始化。
函数
例如,int MultiplyByTwo(int number)第一个int是函数输出的数据类型,第二个是函数的输入类型具体可以看以前写的c语言函数部分,是一样的。
viod start()函数:当这个脚本绑定的对象进入场景时就会调用start函数
(补充:Debug.Log();获取游戏中的任意变量的值)
using UnityEngine;
using System.Collections;
public class VariablesAndFunctions : MonoBehaviour
{
int myInt = 5;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
int MultiplyByTwo (int number)
{
int ret;
ret = number * 2;
return ret;
}
}
3.约定和语法:了解编写代码的一些基本约定和语法:点运算符、分号、缩进和注释。
点运算符:常用于代码内的单词之间,作用是编写一行地址 例: 父.子
分号:作用:终止语句
缩进:并非必须,但方便阅读,特别是体现出层级关系
注释:①//单行注释
② /*hi
*这是一个多行注释
**/
③/**/
using UnityEngine;
using System.Collections;
public class BasicSyntax : MonoBehaviour
{
void Start ()
{
Debug.Log(transform.position.x);
if(transform.position.y <= 5f)
{
Debug.Log ("I'm about to hit the ground!");
}
}
}
4.IF 语句:如何使用 IF 语句在代码中设置条件。
和c语言语法一样
using UnityEngine;
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperatur