U
U
Uncle Bogdan2021-09-19 13:25:41
code review
Uncle Bogdan, 2021-09-19 13:25:41

How can this code (review) be improved?

I wrote this code to move the character when he went off the screen like in Doodle jump.

Can it be improved somehow? And is it bad that it's in Update?

using UnityEngine;

public class Side : MonoBehaviour
{
    [SerializeField] private Transform _oppositePoint; // позиция противоположной стороны
    [SerializeField] private Transform _target; // позиция игрока 

// transform это позиция этой стороны

    [SerializeField] private bool _leftSide;

    private void Awake()
    {
        _leftSide = InitializedSide();
    }

    private void Update()
    {
        if(_leftSide)
        {
            if(transform.position.x > _target.position.x)
            {
                MoveToOppositePoint();
            }
        }
        else
        {
            if (transform.position.x < _target.position.x)
            {
                MoveToOppositePoint();
            }
        }
    }

    private bool InitializedSide() => transform.position.x<_oppositePoint.position.x;

    private void MoveToOppositePoint() => _target.position = new Vector2(_oppositePoint.position.x, _target.position.y);
}


Approximately the same code so that when the player falls to the bottom of the screen, the game restarts.

using UnityEngine;
using UnityEngine.SceneManagement;

public class DeadPoint : MonoBehaviour
{
    [SerializeField] private Transform _target;

    private void Update()
    {
        if(_target.position.y <= transform.position.y)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question