D
D
DmitryLife2019-06-26 12:03:35
Unity
DmitryLife, 2019-06-26 12:03:35

How to refer to a class from another script?

Good afternoon.
I have a very simple question. But I can't find the answer on google.
In Unity, I created 2 scripts, hung them on one object.
In one of the scripts, I created a class and an instance of that class. Filled this instance with data. Now I want to get the data of this instance in another script.
In the second script, I refer to this instance, but it says that there is no such name.
What am I doing wrong.
Code part:

class fightCharacter {
            public int health;

            public void Info () {
                print("Hi!");
            }
        }

void Start()
    {
        fightCharacter char11 = new fightCharacter();
        char11.health = PlayerPrefs.GetInt("char_1_health");
    }

Another script
void Start()
    {
        char11.Info();
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Gaydak, 2019-06-26
@DmitryLife

you have somewhere where a char11 object is created.
if everything is in one script, then the script knows the reference to this object and can reach it.
if in another script, then you need to somehow provide him with information about this object.
how to provide - pass the link directly.
save the reference somewhere in the script that creates the object. or whatever else you can think of.
simply by declaring/creating a variable/object/class inside the method, you will not be able to reach it from anywhere else.
keep the link. learn the basics of C #, the unit is essentially not involved in any way here)
you may even be confused by "two scripts on one object".
Scripts are separate components/classes/objects) the fact that they hang on one GameObject does NOT unite them into one class/object with common variables and references, except for the moment that GetComponent will find them side by side))

F
freeExec, 2019-06-26
@freeExec

Not true Correct

fightCharacter char11 = GetComponent<fightCharacter>();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question