我如何在一个脚本和另一个脚本中使用枚举?

How can i use enum in one script and another script?

在第一个脚本中:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightsEffects : MonoBehaviour
{
    public enum Directions
    {
        Forward, Backward
    };

    private Renderer[] renderers;
    private float lastChangeTime;
    private int greenIndex = 0;

    public void LightsEffect(List<GameObject> objects, Color instantiateColor, Color colorEffect)
    {
        renderers = new Renderer[objects.Count];
        for (int i = 0; i < renderers.Length; i++)
        {
            renderers[i] = objects[i].GetComponent<Renderer>();
            renderers[i].material.color = Color.red;
        }

        // Set green color to the first one
        greenIndex = 0;
        renderers[greenIndex].material.color = Color.green;
    }

    public void LightsEffectCore(float delay, bool changeDirection)
    {
        // Change color each `delay` seconds
        if (Time.time > lastChangeTime + delay)
        {
            lastChangeTime = Time.time;

            // Set color of the last renderer to red
            // and the color of the current one to green
            renderers[greenIndex].material.color = Color.red;
            if (changeDirection == true)
            {
                Array.Reverse(renderers);
                changeDirection = false;
            }
            greenIndex = (greenIndex + 1) % renderers.Length;
            renderers[greenIndex].material.color = Color.green;
        }
    }
}

在此脚本中,我想在核心方法中使用枚举方向而不是布尔值:

public void LightsEffectCore(float delay, bool changeDirection)

改为使用 bool changeDirection 来使用枚举来决定向前或向后的方向。

然后在另一个脚本中使用这个脚本,例如在我做的另一个脚本中:

public LightsEffects lightseffect;

然后在开始:

void Start()
{
 lightseffect.LightsEffect(objects, Color.red, Color.green);
}

然后在更新中我要决定方向:

void Update()
{
  lightseffect.LightsEffectCore(0.1f, false);
}

但是 false/true 我也想在这里使用 Forward/Backward 也许是这样的:

lightseffect.LightsEffectCore(0.1f, lightseffect.Forward);

因为 false/true 并没有真正理解它在做什么。

另一种选择是将其保留为 false/true,但在用户键入时向方法添加说明:lightseffect.LightsEffectCore(

当他打字时(他会看到关于该方法做什么以及他何时打字的描述, 它会告诉他 false/true 会做什么。但是我不知道怎么描述。

Directions 是您感兴趣的枚举的名称。它也包含在 LightsEffects class.

因此在其他地方引用它的方式是 LightsEffects.Directions,然后是另一个点,然后是值(Forward,等等)。这类似于 Fully Qualified Name,但已经声明了该范围的一部分(无论 import/using 让你 LightsEffects)。

所以你的台词:

lightseffect.LightsEffectCore(0.1f, lightseffect.Forward);

变成:

lightseffect.LightsEffectCore(0.1f, LightsEffects.Directions.Forward);

根据您的 IDE,如果您使用 Directions.Forward,它甚至应该能够为您解决这个问题:您的 IDE 会注意到错误(未知参考说明)并建议修复(更改为 LightsEffects.Directions),我知道 Visual Studio 会这样做,因为我现在正在处理的项目中有类似的案例。