Unity的C#编程教程_47_函数和方法
C# Functions and Methods Overview
1. Functions vs. Methods
- 函数和方法其实就是一个东西,在 C# 中通常称之为方法
- 方法,就是一块打包的代码
比如我们最常见的,就是在 Unity 中初始化 C# 脚本的时候出现的两个方法:
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
State()
方法在我们启动游戏的时候会运行
Update()
方法在我们游戏运行过程中进行持续更新操作,每秒 60 帧(60 frames per second)
这个是 Unity 内置的方法,但是同时我们可以创建自己的方法
private void MyMethod()
{
}
这里设定为 private
表示该方法仅在该 class 内部可以调用
如果设定为 public
则别的脚本都可以直接调用该方法
如果我们想调用/运行该方法,比如游戏启动时候调用:
// Start is called before the first frame update
void Start()
{
MyMethod(); // 用 方法名(); 即可
}
前面我们设定的 MyMethod()
方法里面是空的
我们可以尝试添加一些语句,比如:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
MyMethod();
}
// Update is called once per frame
void Update()
{
}
private void MyMethod()
{
Debug.Log("MyMethod is running!");
}
}
则游戏开始的时候就会调用 MyMethod
,运行语句 Debug.Log("MyMethod is running!");
这里 void
指的是没有返回值的函数