Как сделать независимые друг от друга объекты с одинаковыми скриптами на них?

Добрый день. Я рисую линию через LineRenderer и перемещаю объект по точкам этой линии впоследствии.
Есть скрипт DrawManager, который отвечает за создание префаба с линией с компонентом LineRender, есть скрипт Line1, который весит на этом префабе и есть PlayerController который управляет объектом.
Всё работает нормально, но если я создаю клон объекта и пытаюсь от него начать рисовать линию, то всё ломается.

Не пойму, как мне сделать независимые друг от друга эти объекты. Я хочу повесить на сцену 4 объекта, чтобы была возможность рисовать для каждого из них линию и чтобы каждый объект, не обращая внимание на другие линии двигался по своей. Вот код:

DrawManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawManager : MonoBehaviour
{
    private Camera _cam;
    [SerializeField] private Line1 _linePrefab;

    public const float RESOLUTION = .3f;

    private Line1 _currentLine;
    void Start()
    {
        _cam = Camera.main;
    }

    void Update()
    {
        Vector2 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);

        if (Input.GetMouseButtonDown(0) && PlayerController.canDraw) _currentLine = Instantiate(_linePrefab, mousePos, Quaternion.identity);

        if (Input.GetMouseButton(0) && PlayerController.canDraw) _currentLine.SetPosition(mousePos);
    }
}

Line1.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Line1 : MonoBehaviour
{
    [SerializeField] private LineRenderer _renderer;

    private readonly List<Vector2> _points = new List<Vector2>();
    private float _deleteDistance = .5f;

    public void SetPosition(Vector2 pos)
    {
        if (!CanAppend(pos)) return;

        _points.Add(pos);

        _renderer.positionCount++;
        _renderer.SetPosition(_renderer.positionCount - 1, pos);
    }

    private bool CanAppend(Vector2 pos)
    {
        if (_renderer.positionCount == 0) return true;
        
        return Vector2.Distance(_renderer.GetPosition(_renderer.positionCount - 1), pos) > DrawManager.RESOLUTION;
    }

    private void OnDestroy()
    {
        _points.Clear();
        _renderer = new LineRenderer();
    }

    private void Update()
    {
        if (PlayerController.isMoving)
        {
            if (_renderer.positionCount > 0 && Vector2.Distance(_renderer.GetPosition(0), PlayerController.positionGlobal.transform.position) < _deleteDistance)
            {
                _points.RemoveAt(0);
                _renderer.positionCount--;
            }
        }

        if (PlayerController.finalMoving) {
            if (_points.Count > 1)
                _points.Clear();
        }

        UpdateLine();
    }

    private void UpdateLine()
    {
        _renderer.positionCount = _points.Count;

        for (int i = 0; i < _points.Count; i++)
        {
            _renderer.SetPosition(i, _points[i]);
        }
    }

}

PlayerController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed = 10f;
    public float rotationSpeed = 20f;
    public static bool canDraw = false;
    public static bool isMoving = false, finalMoving = false;
    public static Transform positionGlobal;

    [SerializeField]
    private LineRenderer lineRenderer;
    private List<Vector3> linePoints = new List<Vector3>();
    private int targetPointIndex = 0;
    private Vector3 targetPoint, transformParking, centerPosition;
    private Vector3 lastPosition = new Vector3(0f, 0f, 0f), rotationParking;
    private Quaternion rotationCar, endRotation;
    private float lineLength;
    private float elapsedTime;
    private float resolutionPoints = 0.02f;
    public string colorCar;

    void Start()
    {
        lineRenderer = GetComponent<LineRenderer>();
    }

    void Update()
    {
        if (Input.GetMouseButton(0) && canDraw)
        {
            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePosition.z = 0;

            if (mousePosition.x + resolutionPoints <= lastPosition.x || mousePosition.x - resolutionPoints >= lastPosition.x && mousePosition.y + resolutionPoints <= lastPosition.y || mousePosition.y - resolutionPoints >= lastPosition.y)
            {
                linePoints.Add(mousePosition);
            }

            if (lineRenderer != null)
            {
                lineRenderer.positionCount = linePoints.Count;
                lineRenderer.SetPosition(linePoints.Count - 1, mousePosition);
            }
            lastPosition = mousePosition;
        }

        if (Input.GetMouseButtonUp(0))
        {
            lineLength = 0;
            for (int i = 1; i < linePoints.Count; i++)
            {
                lineLength += Vector3.Distance(linePoints[i], linePoints[i - 1]);
            }

            targetPointIndex = 1;

            if (canDraw)
            {
                targetPoint = linePoints[targetPointIndex];

                Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetPoint - transform.position);
                transform.rotation = targetRotation;

                isMoving = true;
                
                Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);

                if (hit.collider != null && hit.collider.gameObject.GetComponent<SpriteRenderer>().sprite.name == colorCar)
                {
                    if (hit.collider.CompareTag("Parking"))
                    {   // Приехали на паркову
                    }
                }
                else
                {
                    CleanCarOpt();
                }
            }
        }

        if (isMoving && linePoints.Count > 1 && targetPointIndex < linePoints.Count)
        {
            Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, targetPoint - transform.position);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

            Vector3 direction = (targetPoint - transform.position).normalized;
            transform.position += direction * speed * Time.deltaTime;

            positionGlobal = transform;

            if (Vector3.Distance(transform.position, targetPoint) < 0.1f)
            {
                targetPointIndex++;
                if (targetPointIndex < linePoints.Count)
                {
                    targetPoint = linePoints[targetPointIndex];
                }
            }
        }
    }

    void OnMouseDown()
    {
        if (Input.GetMouseButtonDown(0))
        {
            canDraw = true;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("DirectEntry"))
        {
            transformParking = collision.gameObject.GetComponentInParent<Transform>().position;
            rotationParking = collision.gameObject.GetComponentInParent<Transform>().eulerAngles;
            Debug.Log(rotationParking);

            centerPosition = new Vector3(transformParking.x / 1f, transformParking.y / 1f, 0f);
            finalMoving = true;
        }
    }

    void CleanCarOpt()
    {
        Quaternion currentRotation = transform.rotation;
        Quaternion newRotation = Quaternion.Euler(currentRotation.eulerAngles.x, currentRotation.eulerAngles.y, 0f);
        transform.rotation = newRotation;

        linePoints.Clear();
        canDraw = false;
        targetPointIndex = 0;
        targetPoint = new Vector3(0f, 0f, 0f);
        lastPosition = new Vector3(0f, 0f, 0f);
        lineLength = 0;
        isMoving = false;

        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Lines");
        if (gameObjects.Length > 0)
        {
            GameObject lastGameObject = gameObjects[gameObjects.Length - 1];
            Destroy(lastGameObject);
        }
    }

}
  • Вопрос задан
  • 36 просмотров
Решения вопроса 1
freeExec
@freeExec
Участник OpenStreetMap
Чтобы объекты были не зависимые они должны использовать только свои локальные переменные. Никаких там статик и управления с клавиатуры.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы