Answer the question
In order to leave comments, you need to log in
Is it possible to write classes in a unit like this?
In the game, I need to create a certain number of moving objects, they have their own speed and coordinates in which they move, but it makes no sense to create a script for each object, so it would be better to do it in the unit inspector so that you can specify how many objects me and set parameters for them
It looks like this
And the script is like this
using System.Linq;
using UnityEngine;
public class ObstacleManager : MonoBehaviour
{
[System.Serializable]
public class ObjectsCoords
{
public GameObject dynamicObstacle; // Объект
public Transform[] dynamicCoords; // Координаты точек, к которым двигается объект
public float speed;
public bool isArrivedSecondCoord; // Прибыл ли объект к точке
}
public ObjectsCoords[] dynamicObj;
// Задаем для объекта начальное положение
void Start()
{
for (int i = 0; i < dynamicObj.Length; i++)
{
dynamicObj[i].dynamicObstacle.transform.position = dynamicObj[i].dynamicCoords[0].position;
}
}
void Update()
{
for (int i = 0; i < dynamicObj.Length; i++)
{
// Если объект прибыл на точку, то меняется булевая переменная, благодаря которой объект отправиться обратно
if (dynamicObj[i].dynamicObstacle.transform.position == dynamicObj[i].dynamicCoords[0].position && dynamicObj[i].isArrivedSecondCoord)
dynamicObj[i].isArrivedSecondCoord = false;
if (dynamicObj[i].dynamicObstacle.transform.position == dynamicObj[i].dynamicCoords[1].position && !dynamicObj[i].isArrivedSecondCoord)
dynamicObj[i].isArrivedSecondCoord = true;
// Задаем координаты, куда будет двигаться объект, если он прибыл на точку, то возвращается обратно
if (!dynamicObj[i].isArrivedSecondCoord)
dynamicObj[i].dynamicObstacle.transform.position = Vector2.MoveTowards(dynamicObj[i].dynamicObstacle.transform.position, dynamicObj[i].dynamicCoords[1].position, dynamicObj[i].speed * Time.deltaTime);
if (dynamicObj[i].isArrivedSecondCoord)
dynamicObj[i].dynamicObstacle.transform.position = Vector2.MoveTowards(dynamicObj[i].dynamicObstacle.transform.position, dynamicObj[i].dynamicCoords[0].position, dynamicObj[i].speed * Time.deltaTime);
}
}
}
Answer the question
In order to leave comments, you need to log in
so you don't have to specify an instance of the class all the time
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question