D
D
Dred Wolf2021-03-30 20:18:01
Unity
Dred Wolf, 2021-03-30 20:18:01

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>() //тут тоже не работает
}
}


i need to save the Rigidbody2D component into a reusable variable through this variable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2021-03-30
@GavriKos

Well, enough to read the error. Actually.

F
Fallerwood, 2021-03-31
@Fallerwood

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>(); 
    }
}

If you need to take it separately from the ball object
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 question

Ask a Question

731 491 924 answers to any question