Как я могу использовать enum с осью Vector3? - PullRequest
1 голос
/ 05 июня 2019
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotate : MonoBehaviour
{
    enum Axistorotate { Back, Down, Forward, Left, Right, Up, Zero};

    public float angle;
    public float speed;
    public Vector3 axis;

    private bool stopRotation = true;
    private Axistorotate myAxis;

    // Start is called before the first frame update
    void Start()
    {
        myAxis = Axistorotate.Left;

        StartCoroutine(RotateObject());
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.S))
        {
            stopRotation = false;
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            stopRotation = true;
            StartCoroutine(RotateObject());
        }
    }

    IEnumerator RotateObject()
    {
        while (stopRotation == true)
        {
            transform.Rotate(Axistorotate.Left, angle);
            yield return new WaitForSeconds(speed);
        }
    }
}

В строке:

transform.Rotate(Axistorotate.Left, angle);

Я хочу использовать enum или сделать что-то, что я смогу выбрать между Vector3.Left или Vector3.Right .... И всеКороткая ось, как enum.

Идея состоит в том, чтобы иметь возможность использовать короткую ось enum или vector3 в этой единственной строке вместо множества строк.

Ответы [ 2 ]

0 голосов
/ 05 июня 2019

На самом деле вы можете сделать это с помощью перечислений, как вы хотите. Вы можете сделать что-то вроде этого:

public class Rotate : MonoBehaviour
{
    public enum Axistorotate { Back, Down, Forward, Left, Right, Up, Zero };
    public Vector3[] vectorAxises = new Vector3[7];

    public Axistorotate myAxis;

Тогда в Start:

void Start()
{
    vectorAxises[0] = Vector3.back;
    vectorAxises[1] = Vector3.down;
    vectorAxises[2] = Vector3.forward;
    vectorAxises[3] = Vector3.left;
    vectorAxises[4] = Vector3.right;
    vectorAxises[5] = Vector3.up;
    vectorAxises[6] = Vector3.zero;

Затем создайте функцию:

public Vector3 GetAxis(Axistorotate axis)
{
    return vectorAxises[(int)axis];
}

А затем используйте это так:

transform.Rotate(GetAxis(Axistorotate.Left), angle);

или

transform.Rotate(GetAxis(myAxis), angle);
0 голосов
/ 05 июня 2019

Вероятно, проще всего использовать константы Vector3 и присвоить их переменной Vector3.Но иногда вы хотите использовать безопасность типов, чтобы гарантировать, что ваш метод не может получить неожиданную ось или Vector3.zero.

Вы не можете сделать это только с enum (вам нужнопереключатель или массив или что-то еще, чтобы интерпретировать enum как Vector3), но вы можете получить нечто подобное и автономное с классом с закрытым конструктором, некоторыми полями только для чтения и методом public static implicit operator Vector3:

public class RotationAxis
{
    public static readonly AxisVector right = new Axis(Vector3.right);
    public static readonly AxisVector left = new Axis(Vector3.left);

    public static readonly AxisVector up = new Axis(Vector3.up);
    public static readonly AxisVector down = new Axis(Vector3.down);

    public static readonly AxisVector forward = new Axis(Vector3.forward);
    public static readonly AxisVector back = new Axis(Vector3.back);

    private Vector3 _value;

    private RotationAxis(Vector3 axis)
    {
        this._value = axis;
    }

    public static implicit operator Vector3(RotationAxis axis) 
    {
        return axis._value;
    }
}

Пример использования:

public void RotateMe(RotationAxis axis, float angle) {
    // using axis as a Vector3 guaranteed by type safety to be one of:
    // Vector3.right/left/up/down/forward/back

    // RotationAxis implicitly converts to Vector3
    transform.Rotate(axis, angle);

    // you can also just use RotationAxis._ as you would Vector3._
    transform.Rotate(RotationAxis.forward, angle);
}

...

RotationAxis axis = RotationAxis.right;
float angle = 45f;
object1.RotateMe(axis, angle);

axis = RotationAxis.up;
angle = 45f;
object2.RotateMe(axis, angle);

// object2.RotateMe(Vector3.zero, angle); would produce a compile error. Can't be done accidentally.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...