Learn Unity - Scripts(新手教程)

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

脚本新手起步

脚本可以作为行为组件

脚本(Scripts)在unity中也作为组件的一种,可以直接附在游戏物体(GameObject)上。有三种方式创建脚本:

  1. 在Project面板中的空旷处右键点击创建(Create)就能看到脚本按钮,即可创建
  2. 在物体的Inspector面板最下方,点击按钮添加组件(Add Component)添加脚本
  3. 选择好物体后,点击顶部菜单栏里的组件(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.");
        }
        // If
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值