脚本新手起步
脚本可以作为行为组件
脚本(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.");
}

本文是一篇Unity新手教程,详细介绍了Unity中脚本的使用,包括脚本作为行为组件、变量和函数、规则与语法、不同语言的比较,以及各种控制结构如IF、循环、范围和访问修饰词。此外,还讲解了Awake、Start、Update、FixedUpdate等生命周期函数,数学向量操作,以及组件的有效性控制、物体激活、移动和旋转。教程还涉及了面向对象编程中的类、实例化、数组、Invoke函数、枚举和Switch语句等内容。
&spm=1001.2101.3001.5002&articleId=50688452&d=1&t=3&u=a3552b486a5f4c29bf5039a0b828363f)
1775

被折叠的 条评论
为什么被折叠?



