0
votes

I have a GameObject that I try to move. For the GameObject I created a new class and this class has a function UpdatePosition(). In this function I update the transform.position of the GameObject and if I log the transform.position of the object, the console writes the newly updated position. However, in the game and scene view in Unity the object does not move. I call the function every tick via an Update function and this works since the Debug.Log outputs to the console every tick. Does anyone know what is going wrong here?

public class ActiveObjects
{
    [SerializeField]
    public GameObject theMovingObject;
    [SerializeField]
    public Transform startPosition;
    [SerializeField]
    public Transform endPosition;

    [NonSerialized]
    private float speed = 10.0f;
    [NonSerialized]
    public float startTime;
    [NonSerialized]
    public float journeyLength;

    // Sets new position of theMovingObject
    public void UpdatePosition()
    {
        float step = speed * Time.deltaTime;
        theMovingObject.transform.position =    Vector3.MoveTowards(theMovingObject.transform.position, endPosition.position, step);
        Debug.log(theMovingObject.transform.position);
    }

}

The output of in the console is the position which theMovingObject should have, but does not have in the game/scene view.

1
I think that MoveTowards only works in the Update(). Can you try? - Andrea
Nope, that does not work. And I guess if MoveTowards would only work in Update(), wouldn't that mean that the values that get logged also not change? Should I attached something like a rigidbody or I don't know what to my object to make it possible to move? - Jorism
You're not inheriting from MonoBehaviour, so this class isn't attached to any game object. Care to show how and from where you call UpdatePosition()? - Galandil
@Galandil I call it from another one of my classes in its update function. This other class does inherit from MonoBehaviour. Code: public class LevelManager : MonoBehaviour { void Update() { foreach(ActiveObjects cue in cueList) { float step = cue.speed * Time.deltaTime; cue.UpdatePosition(); } }} - Jorism
@Jorism, it's better if you edit your post with the code. Code does not present well in comments. - Doh09

1 Answers

0
votes

I did this:

Vector3 newPosition = new Vector3();
newPosition.x = *;
newPosition.y = *;
newPosition.z = *;
transform.position = newPosition;

And if you want Decimal numbers, do this:

newPosition.x = 0.5f;

*Any number

Just to explain:

Vector2 = X, Y

Vector3 = X,Y,Z

Get it? If it doesn't work, just write a comment at this answer. Greetings, Tjovo studios.