找回密码
 立即注册
查看: 247|回复: 0

Unity3d初级编程--Unity官方教程

[复制链接]
发表于 2022-5-6 10:27 | 显示全部楼层 |阅读模式
Unity3d初级编程


      官方链接1.作为行为组件的脚本2.变量和函数3.约定和语法4.IF 语句5.循环6.作用域和访问修饰符7.Awake 和 Start8.Update 和 FixedUpdate9.矢量数学10.启用和禁用组件11.激活游戏对象12.Translate 和 Rotate13.Look At14.线性插值15.Destroy16.GetButton 和 GetKey17.GetAxis18.OnMouseDown19.GetComponent20.DeltaTime21.数据类型22.类23.Instantiate24.数组25.Invoke26.枚举27.Switch 语句


官方链接

官方链接: https://learn.unity.com/project/chu-ji-bian-cheng?uv=4.x
话不多说,直接贴代码。
1.作为行为组件的脚本

Unity 中的脚本是什么?了解作为 Unity 脚本的行为组件,以及如何创建这些脚本并将它们附加到对象。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ExampleBehaviourScript : MonoBehaviour
  4. {
  5.     void Update()
  6.     {
  7.         if (Input.GetKeyDown(KeyCode.R))
  8.         {
  9.             GetComponent<Renderer> ().material.color = Color.red;
  10.         }
  11.         if (Input.GetKeyDown(KeyCode.G))
  12.         {
  13.             GetComponent<Renderer>().material.color = Color.green;
  14.         }
  15.         if (Input.GetKeyDown(KeyCode.B))
  16.         {
  17.             GetComponent<Renderer>().material.color = Color.blue;
  18.         }
  19.     }
  20. }
复制代码
2.变量和函数

什么是变量和函数?它们如何为我们存储和处理信息?
  1. using UnityEngine;
  2. using System.Collections;
  3. public class VariablesAndFunctions : MonoBehaviour
  4. {   
  5.     int myInt = 5;
  6.    
  7.    
  8.     void Start ()
  9.     {
  10.         myInt = MultiplyByTwo(myInt);
  11.         Debug.Log (myInt);
  12.     }
  13.    
  14.    
  15.     int MultiplyByTwo (int number)
  16.     {
  17.         int ret;
  18.         ret = number * 2;
  19.         return ret;
  20.     }
  21. }
复制代码
3.约定和语法

了解编写代码的一些基本约定和语法:点运算符、分号、缩进和注释。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class BasicSyntax : MonoBehaviour
  4. {
  5.     void Start ()
  6.     {
  7.         Debug.Log(transform.position.x);
  8.         
  9.         if(transform.position.y <= 5f)
  10.         {
  11.             Debug.Log ("I'm about to hit the ground!");
  12.         }
  13.     }
  14. }
复制代码
4.IF 语句

如何使用 IF 语句在代码中设置条件。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class IfStatements : MonoBehaviour
  4. {
  5.     float coffeeTemperature = 85.0f;
  6.     float hotLimitTemperature = 70.0f;
  7.     float coldLimitTemperature = 40.0f;
  8.    
  9.     void Update ()
  10.     {
  11.         if(Input.GetKeyDown(KeyCode.Space))
  12.             TemperatureTest();
  13.         
  14.         coffeeTemperature -= Time.deltaTime * 5f;
  15.     }
  16.    
  17.    
  18.     void TemperatureTest ()
  19.     {
  20.         // 如果咖啡的温度高于最热的饮用温度...
  21.         if(coffeeTemperature > hotLimitTemperature)
  22.         {
  23.             // ... 执行此操作。
  24.             print("Coffee is too hot.");
  25.         }
  26.         // 如果不是,但咖啡的温度低于最冷的饮用温度...
  27.         else if(coffeeTemperature < coldLimitTemperature)
  28.         {
  29.             // ... 执行此操作。
  30.             print("Coffee is too cold.");
  31.         }
  32.         // 如果两者都不是,则...
  33.         else
  34.         {
  35.             // ... 执行此操作。
  36.             print("Coffee is just right.");
  37.         }
  38.     }
  39. }
复制代码
5.循环

如何使用 For、While、Do-While 和 For Each 循环在代码中重复操作。
ForLoop
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ForLoop : MonoBehaviour
  4. {
  5.     int numEnemies = 3;
  6.    
  7.    
  8.     void Start ()
  9.     {
  10.         for(int i = 0; i < numEnemies; i++)
  11.         {
  12.             Debug.Log("Creating enemy number: " + i);
  13.         }
  14.     }
  15. }
复制代码
WhileLoop
  1. using UnityEngine;
  2. using System.Collections;
  3. public class WhileLoop : MonoBehaviour
  4. {
  5.     int cupsInTheSink = 4;
  6.    
  7.    
  8.     void Start ()
  9.     {
  10.         while(cupsInTheSink > 0)
  11.         {
  12.             Debug.Log ("I've washed a cup!");
  13.             cupsInTheSink--;
  14.         }
  15.     }
  16. }
复制代码
DoWhileLoop
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DoWhileLoop : MonoBehaviour
  4. {
  5.     void Start()
  6.     {
  7.         bool shouldContinue = false;
  8.         
  9.         do
  10.         {
  11.             print ("Hello World");
  12.             
  13.         }while(shouldContinue == true);
  14.     }
  15. }
复制代码
ForeachLoop
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ForeachLoop : MonoBehaviour
  4. {   
  5.     void Start ()
  6.     {
  7.         string[] strings = new string[3];
  8.         
  9.         strings[0] = "First string";
  10.         strings[1] = "Second string";
  11.         strings[2] = "Third string";
  12.         
  13.         foreach(string item in strings)
  14.         {
  15.             print (item);
  16.         }
  17.     }
  18. }
复制代码
6.作用域和访问修饰符

了解变量和函数的作用域和可访问性。
ScopeAndAccessModifiers
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ScopeAndAccessModifiers : MonoBehaviour
  4. {
  5.     public int alpha = 5;
  6.    
  7.    
  8.     private int beta = 0;
  9.     private int gamma = 5;
  10.    
  11.    
  12.     private AnotherClass myOtherClass;
  13.    
  14.    
  15.     void Start ()
  16.     {
  17.         alpha = 29;
  18.         
  19.         myOtherClass = new AnotherClass();
  20.         myOtherClass.FruitMachine(alpha, myOtherClass.apples);
  21.     }
  22.    
  23.    
  24.     void Example (int pens, int crayons)
  25.     {
  26.         int answer;
  27.         answer = pens * crayons * alpha;
  28.         Debug.Log(answer);
  29.     }
  30.    
  31.    
  32.     void Update ()
  33.     {
  34.         Debug.Log("Alpha is set to: " + alpha);
  35.     }
  36. }
复制代码
AnotherClass
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AnotherClass
  4. {
  5.     public int apples;
  6.     public int bananas;
  7.    
  8.    
  9.     private int stapler;
  10.     private int sellotape;
  11.    
  12.    
  13.     public void FruitMachine (int a, int b)
  14.     {
  15.         int answer;
  16.         answer = a + b;
  17.         Debug.Log("Fruit total: " + answer);
  18.     }
  19.    
  20.    
  21.     private void OfficeSort (int a, int b)
  22.     {
  23.         int answer;
  24.         answer = a + b;
  25.         Debug.Log("Office Supplies total: " + answer);
  26.     }
  27. }
复制代码
7.Awake 和 Start

如何使用 Unity 的两个初始化函数 Awake 和 Start。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AwakeAndStart : MonoBehaviour
  4. {
  5.     void Awake ()
  6.     {
  7.         Debug.Log("Awake called.");
  8.     }
  9.    
  10.    
  11.     void Start ()
  12.     {
  13.         Debug.Log("Start called.");
  14.     }
  15. }
复制代码
8.Update 和 FixedUpdate

如何使用 Update 和 FixedUpdate 函数实现每帧的更改,以及它们之间的区别。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UpdateAndFixedUpdate : MonoBehaviour
  4. {
  5.     void FixedUpdate ()
  6.     {
  7.         Debug.Log("FixedUpdate time :" + Time.deltaTime);
  8.     }
  9.    
  10.    
  11.     void Update ()
  12.     {
  13.         Debug.Log("Update time :" + Time.deltaTime);
  14.     }
  15. }
复制代码
9.矢量数学

矢量数学入门以及有关点积和叉积的信息。
  1. // 无代码
复制代码
10.启用和禁用组件

如何在运行时通过脚本启用和禁用组件。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class EnableComponents : MonoBehaviour
  4. {
  5.     private Light myLight;
  6.    
  7.    
  8.     void Start ()
  9.     {
  10.         myLight = GetComponent<Light>();
  11.     }
  12.    
  13.    
  14.     void Update ()
  15.     {
  16.         if(Input.GetKeyUp(KeyCode.Space))
  17.         {
  18.             myLight.enabled = !myLight.enabled;
  19.         }
  20.     }
  21. }
复制代码
11.激活游戏对象

如何使用 SetActive 和 activeSelf/activeInHierarchy 单独处理以及在层级视图中处理场景内部游戏对象的活动状态。
ActiveObjects
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ActiveObjects : MonoBehaviour
  4. {
  5.     void Start ()
  6.     {
  7.         gameObject.SetActive(false);
  8.     }
  9. }
复制代码
CheckState
  1. using UnityEngine;
  2. using System.Collections;
  3. public class CheckState : MonoBehaviour
  4. {
  5.     public GameObject myObject;
  6.    
  7.    
  8.     void Start ()
  9.     {
  10.         Debug.Log("Active Self: " + myObject.activeSelf);
  11.         Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
  12.     }
  13. }
复制代码
12.Translate 和 Rotate

如何使用两个变换函数 Translate 和 Rotate 来更改非刚体对象的位置和旋转。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class TransformFunctions : MonoBehaviour
  4. {
  5.     public float moveSpeed = 10f;
  6.     public float turnSpeed = 50f;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         if(Input.GetKey(KeyCode.UpArrow))
  12.             transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
  13.         
  14.         if(Input.GetKey(KeyCode.DownArrow))
  15.             transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
  16.         
  17.         if(Input.GetKey(KeyCode.LeftArrow))
  18.             transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
  19.         
  20.         if(Input.GetKey(KeyCode.RightArrow))
  21.             transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
  22.     }
  23. }
复制代码
13.Look At

如何使用 LookAt 函数使一个游戏对象的变换组件面向另一个游戏对象的变换组件。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class CameraLookAt : MonoBehaviour
  4. {
  5.     public Transform target;
  6.    
  7.     void Update ()
  8.     {
  9.         transform.LookAt(target);
  10.     }
  11. }
复制代码
14.线性插值

在制作游戏时,有时可以在两个值之间进行线性插值。这是通过 Lerp 函数来完成的。
  1. // 在此示例中,result = 4
  2. float result = Mathf.Lerp (3f, 5f, 0.5f);
  3. Vector3 from = new Vector3 (1f, 2f, 3f);
  4. Vector3 to = new Vector3 (5f, 6f, 7f);
  5. // 此处 result = (4, 5, 6)
  6. Vector3 result = Vector3.Lerp (from, to, 0.75f);
  7. void Update ()
  8. {
  9.     light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f * Time.deltaTime);
  10. }
复制代码
15.Destroy

如何在运行时使用 Destroy() 函数删除游戏对象和组件。
DestroyBasic
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DestroyBasic : MonoBehaviour
  4. {
  5.     void Update ()
  6.     {
  7.         if(Input.GetKey(KeyCode.Space))
  8.         {
  9.             Destroy(gameObject);
  10.         }
  11.     }
  12. }
复制代码
DestroyOther
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DestroyOther : MonoBehaviour
  4. {
  5.     public GameObject other;
  6.    
  7.    
  8.     void Update ()
  9.     {
  10.         if(Input.GetKey(KeyCode.Space))
  11.         {
  12.             Destroy(other);
  13.         }
  14.     }
  15. }
复制代码
DestroyComponent
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DestroyComponent : MonoBehaviour
  4. {
  5.     void Update ()
  6.     {
  7.         if(Input.GetKey(KeyCode.Space))
  8.         {
  9.             Destroy(GetComponent<MeshRenderer>());
  10.         }
  11.     }
  12. }
复制代码
16.GetButton 和 GetKey

本教程演示如何在 Unity 项目中获取用于输入的按钮或键,以及这些轴的行为或如何通过 Unity Input Manager 进行修改。
KeyInput
  1. using UnityEngine;
  2. using System.Collections;
  3. public class KeyInput : MonoBehaviour
  4. {
  5.     public GUITexture graphic;
  6.     public Texture2D standard;
  7.     public Texture2D downgfx;
  8.     public Texture2D upgfx;
  9.     public Texture2D heldgfx;
  10.    
  11.     void Start()
  12.     {
  13.         graphic.texture = standard;
  14.     }
  15.    
  16.     void Update ()
  17.     {
  18.         bool down = Input.GetKeyDown(KeyCode.Space);
  19.         bool held = Input.GetKey(KeyCode.Space);
  20.         bool up = Input.GetKeyUp(KeyCode.Space);
  21.         
  22.         if(down)
  23.         {
  24.             graphic.texture = downgfx;
  25.         }
  26.         else if(held)
  27.         {
  28.             graphic.texture = heldgfx;
  29.         }
  30.         else if(up)
  31.         {
  32.             graphic.texture = upgfx;
  33.         }
  34.         else
  35.         {
  36.             graphic.texture = standard;
  37.         }
  38.         
  39.         guiText.text = " " + down + "\n " + held + "\n " + up;
  40.     }
  41. }
复制代码
ButtonInput
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ButtonInput : MonoBehaviour
  4. {
  5.     public GUITexture graphic;
  6.     public Texture2D standard;
  7.     public Texture2D downgfx;
  8.     public Texture2D upgfx;
  9.     public Texture2D heldgfx;
  10.    
  11.     void Start()
  12.     {
  13.         graphic.texture = standard;
  14.     }
  15.    
  16.     void Update ()
  17.     {
  18.         bool down = Input.GetButtonDown("Jump");
  19.         bool held = Input.GetButton("Jump");
  20.         bool up = Input.GetButtonUp("Jump");
  21.         
  22.         if(down)
  23.         {
  24.             graphic.texture = downgfx;
  25.         }
  26.         else if(held)
  27.         {
  28.             graphic.texture = heldgfx;
  29.         }
  30.         else if(up)
  31.         {
  32.             graphic.texture = upgfx;
  33.         }
  34.         else
  35.         {
  36.             graphic.texture = standard;
  37.         }
  38.    
  39.         guiText.text = " " + down + "\n " + held + "\n " + up;
  40.     }
  41. }
复制代码
17.GetAxis

如何在 Unity 中为游戏获取基于轴的输入,以及如何通过 Input Manager 修改这些轴。
AxisExample
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AxisExample : MonoBehaviour
  4. {
  5.     public float range;
  6.     public GUIText textOutput;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         float h = Input.GetAxis("Horizontal");
  12.         float xPos = h * range;
  13.         
  14.         transform.position = new Vector3(xPos, 2f, 0);
  15.         textOutput.text = "Value Returned: "+h.ToString("F2");  
  16.     }
  17. }
复制代码
AxisRawExample
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AxisRawExample : MonoBehaviour
  4. {
  5.     public float range;
  6.     public GUIText textOutput;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         float h = Input.GetAxisRaw("Horizontal");
  12.         float xPos = h * range;
  13.         
  14.         transform.position = new Vector3(xPos, 2f, 0);
  15.         textOutput.text = "Value Returned: "+h.ToString("F2");  
  16.     }
  17. }
复制代码
DualAxisExample
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DualAxisExample : MonoBehaviour
  4. {
  5.     public float range;
  6.     public GUIText textOutput;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         float h = Input.GetAxis("Horizontal");
  12.         float v = Input.GetAxis("Vertical");
  13.         float xPos = h * range;
  14.         float yPos = v * range;
  15.         
  16.         transform.position = new Vector3(xPos, yPos, 0);
  17.         textOutput.text = "Horizontal Value Returned: "+h.ToString("F2")+"\nVertical Value Returned: "+v.ToString("F2");   
  18.     }
  19. }
复制代码
18.OnMouseDown

如何检测碰撞体或 GUI 元素上的鼠标点击。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class MouseClick : MonoBehaviour
  4. {
  5.     void OnMouseDown ()
  6.     {
  7.         rigidbody.AddForce(-transform.forward * 500f);
  8.         rigidbody.useGravity = true;
  9.     }
  10. }
复制代码
19.GetComponent

如何使用 GetComponent 函数来处理其他脚本或组件的属性。
UsingOtherComponents
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UsingOtherComponents : MonoBehaviour
  4. {
  5.     public GameObject otherGameObject;
  6.    
  7.    
  8.     private AnotherScript anotherScript;
  9.     private YetAnotherScript yetAnotherScript;
  10.     private BoxCollider boxCol;
  11.    
  12.    
  13.     void Awake ()
  14.     {
  15.         anotherScript = GetComponent<AnotherScript>();
  16.         yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
  17.         boxCol = otherGameObject.GetComponent<BoxCollider>();
  18.     }
  19.    
  20.    
  21.     void Start ()
  22.     {
  23.         boxCol.size = new Vector3(3,3,3);
  24.         Debug.Log("The player's score is " + anotherScript.playerScore);
  25.         Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
  26.     }
  27. }
复制代码
AnotherScript
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AnotherScript : MonoBehaviour
  4. {
  5.     public int playerScore = 9001;
  6. }
复制代码
YetAnotherScript
  1. using UnityEngine;
  2. using System.Collections;
  3. public class YetAnotherScript : MonoBehaviour
  4. {
  5.     public int numberOfPlayerDeaths = 3;
  6. }
复制代码
20.DeltaTime

什么是 Delta Time?如何在游戏中将其用于对值进行平滑和解释?
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UsingDeltaTime : MonoBehaviour
  4. {
  5.     public float speed = 8f;
  6.     public float countdown = 3.0f;
  7.    
  8.     void Update ()
  9.     {
  10.         countdown -= Time.deltaTime;
  11.         if(countdown <= 0.0f)
  12.             light.enabled = true;
  13.         
  14.          if(Input.GetKey(KeyCode.RightArrow))
  15.             transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
  16.     }   
  17. }
复制代码
21.数据类型

了解“值”和“引用”数据类型之间的重要区别,以便更好地了解变量的工作方式。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class DatatypeScript : MonoBehaviour
  4. {
  5.     void Start ()
  6.     {
  7.         //值类型变量
  8.         Vector3 pos = transform.position;
  9.         pos = new Vector3(0, 2, 0);
  10.         
  11.         //引用类型变量
  12.         Transform tran = transform;
  13.         tran.position = new Vector3(0, 2, 0);
  14.     }
  15. }
复制代码
22.类

如何使用类来存储和组织信息,以及如何创建构造函数以便处理类的各个部分。
SingleCharacterScript
  1. using UnityEngine;
  2. using System.Collections;
  3. public class SingleCharacterScript : MonoBehaviour
  4. {
  5.     public class Stuff
  6.     {
  7.         public int bullets;
  8.         public int grenades;
  9.         public int rockets;
  10.         
  11.         public Stuff(int bul, int gre, int roc)
  12.         {
  13.             bullets = bul;
  14.             grenades = gre;
  15.             rockets = roc;
  16.         }
  17.     }
  18.    
  19.    
  20.     public Stuff myStuff = new Stuff(10, 7, 25);
  21.     public float speed;
  22.     public float turnSpeed;
  23.     public Rigidbody bulletPrefab;
  24.     public Transform firePosition;
  25.     public float bulletSpeed;
  26.    
  27.    
  28.     void Update ()
  29.     {
  30.         Movement();
  31.         Shoot();
  32.     }
  33.    
  34.    
  35.     void Movement ()
  36.     {
  37.         float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
  38.         float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
  39.         
  40.         transform.Translate(Vector3.forward * forwardMovement);
  41.         transform.Rotate(Vector3.up * turnMovement);
  42.     }
  43.    
  44.    
  45.     void Shoot ()
  46.     {
  47.         if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
  48.         {
  49.             Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position,                                                                                 firePosition.rotation) as Rigidbody;
  50.             bulletInstance.AddForce(firePosition.forward * bulletSpeed);
  51.             myStuff.bullets--;
  52.         }
  53.     }
  54. }
复制代码
Inventory
  1. using UnityEngine;
  2. using System.Collections;
  3. public class Inventory : MonoBehaviour
  4. {
  5.     public class Stuff
  6.     {
  7.         public int bullets;
  8.         public int grenades;
  9.         public int rockets;
  10.         public float fuel;
  11.         
  12.         public Stuff(int bul, int gre, int roc)
  13.         {
  14.             bullets = bul;
  15.             grenades = gre;
  16.             rockets = roc;
  17.         }
  18.         
  19.         public Stuff(int bul, float fu)
  20.         {
  21.             bullets = bul;
  22.             fuel = fu;
  23.         }
  24.         
  25.         // 构造函数
  26.         public Stuff ()
  27.         {
  28.             bullets = 1;
  29.             grenades = 1;
  30.             rockets = 1;
  31.         }
  32.     }
  33.    
  34.     // 创建 Stuff 类的实例(对象)
  35.     public Stuff myStuff = new Stuff(50, 5, 5);
  36.    
  37.     public Stuff myOtherStuff = new Stuff(50, 1.5f);
  38.    
  39.     void Start()
  40.     {
  41.         Debug.Log(myStuff.bullets);
  42.     }
  43. }
复制代码
MovementControls
  1. using UnityEngine;
  2. using System.Collections;
  3. public class MovementControls : MonoBehaviour
  4. {
  5.     public float speed;
  6.     public float turnSpeed;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         Movement();
  12.     }
  13.    
  14.    
  15.     void Movement ()
  16.     {
  17.         float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
  18.         float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
  19.         
  20.         transform.Translate(Vector3.forward * forwardMovement);
  21.         transform.Rotate(Vector3.up * turnMovement);
  22.     }
  23. }
复制代码
Shooting
  1. using UnityEngine;
  2. using System.Collections;
  3. public class Shooting : MonoBehaviour
  4. {
  5.     public Rigidbody bulletPrefab;
  6.     public Transform firePosition;
  7.     public float bulletSpeed;
  8.    
  9.    
  10.     private Inventory inventory;
  11.    
  12.    
  13.     void Awake ()
  14.     {
  15.         inventory = GetComponent<Inventory>();
  16.     }
  17.    
  18.    
  19.     void Update ()
  20.     {
  21.         Shoot();
  22.     }
  23.    
  24.    
  25.     void Shoot ()
  26.     {
  27.         if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
  28.         {
  29.             Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position,                                                                    firePosition.rotation) as Rigidbody;
  30.             bulletInstance.AddForce(firePosition.forward * bulletSpeed);
  31.             inventory.myStuff.bullets--;
  32.         }
  33.     }
  34. }
复制代码
23.Instantiate

如何在运行期间使用 Instantiate 创建预制件的克隆体。
UsingInstantiate
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UsingInstantiate : MonoBehaviour
  4. {
  5.     public Rigidbody rocketPrefab;
  6.     public Transform barrelEnd;
  7.    
  8.    
  9.     void Update ()
  10.     {
  11.         if(Input.GetButtonDown("Fire1"))
  12.         {
  13.             Rigidbody rocketInstance;
  14.             rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
  15.             rocketInstance.AddForce(barrelEnd.forward * 5000);
  16.         }
  17.     }
  18. }
复制代码
RocketDestruction
  1. using UnityEngine;
  2. using System.Collections;
  3. public class RocketDestruction : MonoBehaviour
  4. {
  5.     void Start()
  6.     {
  7.         Destroy (gameObject, 1.5f);
  8.     }
  9. }
复制代码
24.数组

使用数组将变量集合在一起以便于管理。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class Arrays : MonoBehaviour
  4. {
  5.     public GameObject[] players;
  6.     void Start ()
  7.     {
  8.         players = GameObject.FindGameObjectsWithTag("Player");
  9.         
  10.         for(int i = 0; i < players.Length; i++)
  11.         {
  12.             Debug.Log("Player Number "+i+" is named "+players[i].name);
  13.         }
  14.     }
  15. }
复制代码
25.Invoke

Invoke 函数可用于安排在以后的时间进行方法调用。在本视频中,您将学习如何在 Unity 脚本中使用 Invoke、InvokeRepeating 和 CancelInvoke 函数。
InvokeScript
  1. using UnityEngine;
  2. using System.Collections;
  3. public class InvokeScript : MonoBehaviour
  4. {
  5.     public GameObject target;
  6.    
  7.    
  8.     void Start()
  9.     {
  10.         Invoke ("SpawnObject", 2);
  11.     }
  12.    
  13.     void SpawnObject()
  14.     {
  15.         Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
  16.     }
  17. }
复制代码
InvokeRepeating
  1. using UnityEngine;
  2. using System.Collections;
  3. public class InvokeRepeating : MonoBehaviour
  4. {
  5.     public GameObject target;
  6.    
  7.    
  8.     void Start()
  9.     {
  10.         InvokeRepeating("SpawnObject", 2, 1);
  11.     }
  12.    
  13.     void SpawnObject()
  14.     {
  15.         float x = Random.Range(-2.0f, 2.0f);
  16.         float z = Random.Range(-2.0f, 2.0f);
  17.         Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
  18.     }
  19. }
复制代码
26.枚举

枚举可用于创建相关常量的集合。在本视频中,您将学习如何在代码中声明和使用枚举。
  1. public class EnumScript : MonoBehaviour
  2. {
  3.     enum Direction {North, East, South, West};
  4.         void Start ()
  5.     {
  6.         Direction myDirection;
  7.         
  8.         myDirection = Direction.North;
  9.     }
  10.    
  11.     Direction ReverseDirection (Direction dir)
  12.     {
  13.         if(dir == Direction.North)
  14.             dir = Direction.South;
  15.         else if(dir == Direction.South)
  16.             dir = Direction.North;
  17.         else if(dir == Direction.East)
  18.             dir = Direction.West;
  19.         else if(dir == Direction.West)
  20.             dir = Direction.East;
  21.         
  22.         return dir;     
  23.     }
  24. }
复制代码
27.Switch 语句

Switch 语句的作用类似于简化条件。当您希望将单个变量与一系列常量进行比较时,这类语句很有用。在本视频中,您将学习如何编写和使用 switch 语句。
  1. using UnityEngine;
  2. using System.Collections;
  3. public class ConversationScript : MonoBehaviour
  4. {
  5.     public int intelligence = 5;
  6.    
  7.    
  8.     void Greet()
  9.     {
  10.         switch (intelligence)
  11.         {
  12.         case 5:
  13.             print ("Why hello there good sir! Let me teach you about Trigonometry!");
  14.             break;
  15.         case 4:
  16.             print ("Hello and good day!");
  17.             break;
  18.         case 3:
  19.             print ("Whadya want?");
  20.             break;
  21.         case 2:
  22.             print ("Grog SMASH!");
  23.             break;
  24.         case 1:
  25.             print ("Ulg, glib, Pblblblblb");
  26.             break;
  27.         default:
  28.             print ("Incorrect intelligence level.");
  29.             break;
  30.         }
  31.     }
  32. }
复制代码
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2025-5-3 14:34 , Processed in 0.326047 second(s), 25 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表