编写方法
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 39 课,共 85 课。
你已经调用方法一段时间了:Debug.Log、PlaceCrate,而 Unity 会调用你的 Start() 和 Update()。自己编写方法也是一样的:
void Shout(string word)
{
Debug.Log(word + "!");
}void 表示这个方法会执行一个任务,但不会返回任何内容。Shout 是它的名称。括号内是它的参数:由调用方填入的变量。Shout("Hello"); 会运行这个方法,此时 word 的值为 "Hello";Shout("Run"); 则会再次运行它,此时 word 的值为 "Run"。
没有参数的方法仍然需要一对空括号:void Jump(),调用时写作 Jump();。一个方法可以接受多个参数,用逗号分隔:void PlaceTile(int column, int row)。
挑战
中等给 PlaceLamp 添加一个参数,让每盏灯都放在自己的位置。
- 将方法的第一行改为
void PlaceLamp(float x),并将位置改为new Vector3(x, 1, 0)。 - 在
Start()中,将调用改为PlaceLamp(-3);、PlaceLamp(0);和PlaceLamp(3);。
按“开始”:三盏灯排成一行,彼此相距 3。然后按“检查”。
亲手试试
using UnityEngine;
public class LampRow : MonoBehaviour
{
void Start()
{
PlaceLamp();
PlaceLamp();
PlaceLamp();
}
void PlaceLamp()
{
GameObject lamp = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
lamp.name = "Lamp";
lamp.transform.position = new Vector3(0, 1, 0);
lamp.transform.localScale = new Vector3(0.3f, 1, 0.3f);
lamp.GetComponent<Renderer>().material.color = new Color(0.3f, 0.3f, 0.35f);
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器