脚本新手起步
脚本可以作为行为组件
脚本(Scripts)在unity中也作为组件的一种,可以直接附在游戏物体(GameObject)上。有三种方式创建脚本:
- 在Project面板中的空旷处右键点击创建(Create)就能看到脚本按钮,即可创建
- 在物体的Inspector面板最下方,点击按钮添加组件(Add Component)添加脚本
- 选择好物体后,点击顶部菜单栏里的组件(Component),点击Add添加新组件或者点击脚本(Scripts)添加现有的脚本组件
变量和函数
变量形式: 类型 变量名 = 值; (type nameOfVariable = value;)
函数形式: 类型 函数名(类型 参数名); (type FunctionName(type parameterName);)
规则与语法
语法与C#大体类似,空行,末尾分号,注释等这里不再赘述
JS VS C# 语法
using UnityEngine;
using System.Collections;
public class ExampleSyntax : MonoBehaviour
{
int myInt = 5;
int MyFunction (int number)
{
int ret = myInt * number;
return ret;
}
}
#pragma strict
var myInt : int = 5;
function MyFunction (number : int) : int
{
var ret = myInt * number;
return ret;
}
在此写出同含义的两个语言代码作为对比,需要提到的是上文C#中的变量默认是私有(private)的,而JS中的变量是公有(public)的
IF语句
范例
using UnityEngine;
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
// If the coffee''s temperature is greater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
{
// ... do this.
print("Coffee is too hot.");
}
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... do this.
print("Coffee is too cold.");
}