Unity:如何保证测试代码只在Unity编译器中执行

在unity写代码的时候,通常我们会写出一部分效果就测试一下,这时候又可能会在脚本中写测试代码来查看效果是否符合预期。为了防止我们写完测试代码但是又忘记删除掉了,导致游戏可能有些神奇的bug,我们采用下面的方式去防止出现这个问题。

具体语法非常简单:

#if UNITY_EDITOR


    //编译器环境下的代码逻辑


#endif

相反,不在编译器环境下运行的代码语法:只需要加一个 ! 符号就好了

#if !UNITY_EDITOR


    //编译器环境下的代码逻辑


#endif

 代码示例如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// boss的控制脚本,移动,攻击,受伤
/// </summary>
public class BossTankController : MonoBehaviour
{
    public enum bossState { shooting, hurt, moving};    //状态机
    public bossState currentState;

    private void Start()
    {
        currentState = bossState.shooting;
    }

    private void Update()
    {
        switch (currentState)
        {
            case bossState.shooting:

                break;
            case bossState.hurt:
                if (hurtCounter > 0)
                {
                    hurtCounter -= Time.deltaTime;
                    if (hurtCounter <= 0)
                    {
                        currentState = bossState.moving;        //从受伤状态变成移动状态
                    }
                }
                break;
            case bossState.moving:

                break;
            default:
                break;
        }

#if UNITY_EDITOR

        if (Input.GetKeyDown(KeyCode.K))
        {
            TakeHit();
        }

#endif

    }

    public void TakeHit()
    {
        currentState = bossState.hurt;
        hurtCounter = hurtTime;
    }
}

这样就有效减少我们写测试代码忘记删除而出现的某些问题了。

而且,我们也可以在里面开一下挂,方便自己在测试的时候更方便的测试出效果。

如果想了解更多可以查看:

Unity3d | 关于 if UNITY_EDITOR - 知乎 (zhihu.com)icon-default.png?t=O83Ahttps://zhuanlan.zhihu.com/p/134642925#:~:text=%23if%20UNITY_或者网上搜索学习并运用

猜你喜欢

转载自blog.csdn.net/QA154/article/details/142502029