更详细讲解:
【Unity 05】C# static类及其使用方法
上面有详细介绍,有个流程图很好说明了静态方法和成员方法间的调用权限关系:
这里记录一下自己在使用中的一些情况;
1、脚本说明
普通类TestStatic中,定义了一个static方法DebugLogName(),在该类内部Update中会调用静态方法DebugLogName
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestStatic : MonoBehaviour
{
public static string debugName;
// Start is called before the first frame update
void Start()
{
debugName = gameObject.name;
Debug.Log(debugName);
}
public static void DebugLogName(string name)
{
Debug.Log("打印脚本所在对象名称:" + name);
}
// Update is called once per frame
void Update()
{
DebugLogName("这里是在类内部调用的: " + gameObject.name);
}
}
BtnClick脚本挂在场景中某个物体上,用来在Update中调用TestStatic类中的静态方法DebugLogName;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BtnClick : MonoBehaviour
{
// Update is called once per frame
void Update()
{
TestStatic.DebugLogName("这里是在类外部调用: " + TestStatic.debugName);
}
}
2、场景布局
新建三个物体,其中两个挂载TestStatic脚本,另一个挂载BtnClick脚本;
3、运行后打印信息
根据打印信息,两个TestStatic脚本内部调用DebugLogName静态方法,打印信息数量与BtnClick脚本外部调用TestStatic.DebugLogName的次数相同,而且打印列表中只有一个外部打印信息;
说明虽然场景中挂载了多个该脚本,但该脚本中的静态方法,通过外部调用时,只执行一次;而不是像内部调用静态方法那样,场景中每个脚本都会执行;