Y
Y
yraiv2022-01-23 20:58:42
Unity
yraiv, 2022-01-23 20:58:42

How to pass data to another script?

How to pass data to another script? I am creating an object in my script and I need to pass some int and float data to it, how can I do this? but not through find, namely, when creating, somehow give the data to it.
I create like this

Rigidbody2D clone = Instantiate(bullet, gunPoint.position, Quaternion.identity) as Rigidbody2D;
            clone.velocity = transform.TransformDirection(gunPoint.right * speed);
            clone.transform.right = gunPoint.right;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2022-01-23
@GavriKos

You are creating an object, not a script. Take the desired script (component) (GetComponent) from the object and pass it to it.
Specifically at creation - in any way. Only immediately after creation

N
Nekit Medvedev, 2022-01-24
@NIKROTOS

Make this data public/make a public method that will return it.
On the component that needs data, create the required public object/variables.
After that, you can drag an object (variables) with this data (method) from the object / scene tree to the public variable of the component that needs this data, it will find the required component itself and create a link to it. We call a variable/method by reference. Can be done through code using GetComponent.
Search by tags / component name, I do not recommend using it, you can try to implement a connection through a hierarchy.
There is also a singleton pattern, such an object can be referenced from anywhere in the program, but it must be in a single instance. You can make the object from which information is required, a loner, or transfer this data through a loner.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question