G
G
Gleb Coller2022-02-12 19:57:59
C++ / C#
Gleb Coller, 2022-02-12 19:57:59

How can data be transferred from one script to another?

What is the problem. I have two scripts. One with Coins data, the other Player. There is a coinsAmount variable in the Coins script. I need to miraculously transfer this variable with this value to the Player script.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2022-02-12
@vabka

You can only move the variable itself with ctrl+X -> ctrl+V. And this is how you can transfer the data that is stored in it:
Option once: access the data about the coins directly through the field/property of the class instance.
More or less like this:

public class Player {
  public Coins coins; // Как-то нужно присвоить ему значение, иначе будет NRE
  public void SomeMethod() {
    var total = coins.coinsAmount; // Вот мы и обратились
  }
}

Option two: pass the value as a method parameter where this data is needed.
The choice depends on when the data is needed. It is impossible to be more specific, because there is not enough information in your question
And since you are asking a question in the "C #" tag, then use the normal terminology:
Not scripts, but classes.
Not a variable, but a field.

M
mordamax1, 2022-02-27
@mordamax1

In the Coins script, the coinsAmount variable needs to be made public if it is not.
In the Player script, you need to create a variable that will contain the coinsAmount data (assume that the variable is called coinsAmountPlayer) and write in the update:
coinsAmountPlayer = GameObject.Find("SomeObject").GetComponent().coinsAmount; //Instead of SomeObject, you need to write the name of the object to which the script will be attached.
Perhaps this is a fig method in terms of optimization, but the result should be

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question