Transform.position doesn't change if I use variable, but it does if I hardcode it

What I want to do:

I have a cube that once a character object collides with it, I want it to call the Action() method of a list of objects associated with it, for example A Door Object will go up or down as in opening.

The issue:

On the Action method I have this line:

gameObject.transform.position += new Vector3(0, 1, 0);

which correctly moves the object a few units up.

However, what I want its for this to work:

gameObject.transform.position += new Vector3(0, direction, 0);
direction *= -1;

Essentially have a variable that changes from up to down each time Action is called.

This is the fullscript:

public class DoorHandle : MonoBehaviour
{
    // Start is called before the first frame update
    int direction;
    void Start()
    {
        direction = 1;
    }
    public void Action()
    {
        Debug.Log("Calling Action");
        gameObject.transform.position += new Vector3(0, direction, 0);
        // Reverse direction for the next action call
        direction *= -1;
    }
}

For somereason, this doesn’t work. The Y position doesn’t change at all.

What I have tried:

I have tried changing it to this.direction, I have changed it from public to private, I have assigned at Class level. I have no idea why it doesn’t work when I use the variable direction and why it works if I just hard code it, I have a similar object that calls a a similar function with Update and it moves correctly.

What may be happening is that for some reason your action is being called multiple times and so the door opens and then instantly closes again making you think that it’s not working. Whereas when you hard code it the door is always going in one direction. A tell tale sign is that you said it moves the door a few units up and yet Vector3(0,1,0) should only move the door one unit.

Not sure why yours isn’t working. This is essentially the same thing and it works fine:

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

public class DoorHandle : MonoBehaviour
{
    int direction = 1;
    public float amount = 3; // scale the amount of movement if desired

    void Start()
    {
        InvokeRepeating("Action", 2f, 2f);
    }
    public void Action()
    {
        Debug.Log("Calling Action");
        gameObject.transform.position += new Vector3(0, direction * amount, 0);
        // Reverse direction for the next action call
        direction *= -1;
    }
}

Thanks everyone! The issue was twofold:

First, my Character had a child collider object, I didn’t know the children inherited the parents layer for collisions, so I was detecting it twice per frame, essentially negating the movement.

Second, for some reason I had 2 colliders in the cube I was interacting with, which was also getting triggered twice.

Once I fixed the layers interactions and removed the second collider, it worked correctly.

Thank you for your help!