- Home /
How to use enum switch case and Update ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallsTest : MonoBehaviour {
public enum AxisTest {OnX, OnZ};
public AxisTest axis;
private string SelectedAxis;
// Use this for initialization
void Start ()
{
axis = AxisTest.OnZ;
switch (axis)
{
case AxisTest.OnX:
SelectedAxis = "OnX";
break;
case AxisTest.OnZ:
SelectedAxis = "OnZ";
break;
}
}
// Update is called once per frame
void Update ()
{
if (SelectedAxis == "OnX")
{
if (transform.localScale.x != 100)
{
transform.localScale += new Vector3(1, 1, 0);
transform.localPosition += new Vector3(0.5f, 0.5f, 0);
}
}
if (SelectedAxis == "OnZ")
{
if (transform.localScale.z != 100)
{
transform.localScale += new Vector3(0, 1, 1);
transform.localPosition += new Vector3(0, 0.5f, 0.5f);
}
}
}
}
In the Start if i make axis = AxisTest.OnZ; it will do the Z part in the Update even if i select OnX in the Inspector.
First why it's not doing the selected option in the inspector ?
Second how can i make the whole code shorter ? Maybe without enum case switch ? In the future i will have more options in the enum.
Answer by MaxGuernseyIII · Oct 12, 2017 at 06:55 PM
The problem is that your Start() method forces the axis to be OnZ.
I think your intention was for the default value to be OnZ. That can be accomplished by changing where you set axis to OnZ.
public AxisTest axis = AxisTest.OnZ;
Then take out the line where you initialize that value in Start().
Answer by keithloganbecker · Oct 12, 2017 at 06:41 PM
I can tell you arn't very experienced writing c# code. The switch statement you are using accomplishes nothing. In the code you wrote SelectedAxis will always end up as "OnZ", it will never be "OnX"
This is equivalent code to what you wrote in Start() method, it does the same thing:
void Start() {
SelectedAxis = "OnZ";
}