Creating an Enum as the parameter to the Steer() function

Greetings

Instead of using int values to track if my car is steering left or right (and remembering which one is which) I thought of using an enum with those values.

[Serializable]
public enum SteerDirection
{
    Left = -1,
    Right = 1,
    None = 0
}

However when I try to associate my Steer(SteerDirection value) on the inspector, this does not show up. I tried adding the serializable tag, or updating some of the references in the Car.cs class.

I was wondering if anyone had a similar experience, or if there’s any arguments against this approach. On regular non-engine programming it is recommended to avoid “magic numbers” so that was my attempted approach here.

Note: Tagging as talk, as it’s more for discussion than a direct quesion. I can continue the lesson using magic numbers :slight_smile:

Might be best to look this up on a forum to see if SerializeField etc can be used with enum values.

This worked for me

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

public class Car : MonoBehaviour
{
    public enum SteerDirection
    {
        Left = -1,
        Right = 1,
        None = 0
    }

    [SerializeField] private float speed = 10f;
    [SerializeField] private float speedGainOverTime = 0.2f;
    [SerializeField] private float turnSpeed = 200f;
    [SerializeField] private SteerDirection steerDirection = SteerDirection.None;

    void Update()
    {
        speed += speedGainOverTime * Time.deltaTime;

        transform.Rotate(0f, (float)steerDirection * turnSpeed * Time.deltaTime, 0f);

        transform.Translate(Vector3.forward * speed * Time.deltaTime);

    }

    public void Steer(int value)
    {
        if(value == -1)
        {
            steerDirection = SteerDirection.Left;
        }
        else if(value == 1)
        {
            steerDirection = SteerDirection.Right;
        }
        else if(value == 0)
        {
            steerDirection = SteerDirection.None;
        }

    }
}

Privacy & Terms