P
P
PRIYD2020-05-09 12:17:08
C++ / C#
PRIYD, 2020-05-09 12:17:08

Why are objects not moving?

Hello, there is a certain number of objects that must move. When calling the PlayerWalking function (PlayerMovement class) from another script (Test), nothing happens (if you call it in PlayerMovement, then everything works). Help me to understand.

PlayerMovement class code:

public class PlayerMovement : MonoBehaviour
{
    private float _playerSpeed = 500f; 

    // Ходьба осуществляется в соответствии с заданым направлением, пример: (1, 0, 0); (1, 0, -1)...
    public void PlayerWalking(Vector3 movementVector, float movementCoefficient) 
    {
        float playerDirectionX = movementVector.x;
        float playerDirectionZ = movementVector.z;
        
        gameObject.transform.Translate(
            Vector3.forward * _playerSpeed * playerDirectionX * movementCoefficient * Time.deltaTime + 
            Vector3.right * _playerSpeed * playerDirectionZ * movementCoefficient * Time.deltaTime);       
    }

}


Test class code:
public class Test : MonoBehaviour
{
    private List<GameObject> objects;
    private PlayerMovement playerMovement;

    void Update()
    {
        objects = FindInActiveObjectsByTag("Player");

        for (int n = 0; n < objects.Count; n++)
        {
            playerMovement = objects[n].GetComponent<PlayerMovement>();
            playerMovement.PlayerWalking(new Vector3(1f, 0f, 1f), 1f);
        }           
    }

    // Функция, которая находит все объекты с определенным тегом
    private List<GameObject> FindInActiveObjectsByTag(string tag)
    {
        List<GameObject> validTransforms = new List<GameObject>();
        Transform[] objs = Resources.FindObjectsOfTypeAll<Transform>() as Transform[];

        for (int i = 0; i < objs.Length; i++)
        {
            if (objs[i].hideFlags == HideFlags.None)
            {
                if (objs[i].gameObject.CompareTag(tag))
                {
                    validTransforms.Add(objs[i].gameObject);
                }
            }
        }
        return validTransforms;
    }
}


As far as I understood from the tests, the links to all objects work, but the movement does not occur

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PRIYD, 2020-05-09
@PRIYD

The objects didn't move because the function was called 1 time. Changed it to call PlayerWalking() in Update() and just made a function to change direction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question