Answer the question
In order to leave comments, you need to log in
How to pass the position of an object to a script that hangs on another object without being included in the inspector?
How to pass the position of an object to a script that hangs on another object without being included in the inspector? There are two objects (a ball and a cube) that must be synchronized, that is, when the cube moves, the ball must also move. Without using the inspector. It might be worth using triggers, but it will clutter up the scene. I created a script for the ball, where I assigned a Rigidbody and through it I tried to get access to the movement of the ball in the cube script, but it does not work out. I don't want to use Find, because in the future there will be a lot of objects on the stage and I don't want to complicate the process.
Answer the question
In order to leave comments, you need to log in
Make yourself a MovementSyncer.cs script and write the following code in it
[SerializedField] private bool isLeader; //переменная указывает, что данный объект лидер, а остальные повторяют
[SerializedField] private string category; //переменная для разделения объектов на категории, например категория "синие", "красные"
private MovementSyncer leader; //переменная для кеширования лидера на старте
private void Awake()
{
//найди объект-лидер для данной категории
leader= FindObjectsOfType<MovementSyncer>().First(ms => ms.category == category && ms.isLeader);
}
private void Update()
{
if (isLeader) return; //пропускаем себя, еcли лидер
transform.position = leader.transform.position;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question