Answer the question
In order to leave comments, you need to log in
How can I put a game object component into a variable?
Since I use the Rigidbody2D component of the game object a lot, I decided to put it in a variable, is it possible? For some reason, my code does not work:
firstly, it is not possible to create such a variable as a class property
public class PingPong : MonoBehaviour
{
public Transform ball;
Rigidbody2D ballRb = ball.GetComponent<Rigidbody2D>() //тут ошибка
void Start(){
Rigidbody2D ballRb = ball.GetComponent<Rigidbody2D>() //тут тоже не работает
}
}
Answer the question
In order to leave comments, you need to log in
This will work if this script hangs on the object along with RigidBody2D
public class PingPong : MonoBehaviour
{
public Transform ball;
Rigidbody2D ballRb; // Объявляем переменную ballRb с типом RigidBody2D, на этом этапе, она пустая
void Start()
{
// Присвоение переменной локального (который висит вместе со скриптом) RigidBody2D
ballRb = GetComponent<Rigidbody2D>();
}
}
public class PingPong : MonoBehaviour
{
public GameObject ball; // Переменная должна быть игровым объектом
Rigidbody2D ballRb; // Объявляем переменную ballRb с типом RigidBody2D, на этом этапе, она пустая
void Start()
{
// Присвоение переменной от объекта ball RigidBody2D
ballRb = ball.GetComponent<Rigidbody2D>();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question