Sean Sabe
Sean Sabe

Reputation: 79

Using variables from another script int Unity 5

I need to use some variables defined in a script but when I call them their values are 0. I don't know what I am doing wrong.

Example:

Script1.cs

public int cont;


public void Method() { cont++; }

void Update() { Method(); }

Script2.cs

public Script1 usingScript1;

void MethodX()
{
    usingScript1.GetComponent<Script1>();
    Debug.Log(usingScript1.cont);
}

void Update() { MethodX(); }

This script should be showing the "cont" variable increasing since it's being called from Update(), but that's not happening. When I call it, it's 0 and don't increase.

Also, I refer the object which contains Script1.cs in the Ispector. It must be a simple thing that I'm missing. I even tried calling Method().

Upvotes: 0

Views: 985

Answers (3)

Sean Sabe
Sean Sabe

Reputation: 79

I managed to solve it and never thought about it. As simple as it. Instad of creating an object, I just made the variables static and call 'em using the class.

Script1.cs

public static cont;

Script2.cs

Script1.cont;

And it works.

Upvotes: 0

mnaa
mnaa

Reputation: 424

Just to add to what everyone mentioned, have you tried initializing "cont" ?

This

public int cont;

becomes

public int cont = 0; 

Also try initializing it in the Start() function if this doesn't work.

Upvotes: 2

HalpPlz
HalpPlz

Reputation: 701

The function called Method() is never called anywhere in this code. Since it's the only thing that modifies the value of the variable called cont, if it is never called, cont will never change from its default value of zero.

EDIT: Whoops! Okay, the actual problem here is that you need to change

usingScript1.GetComponent<Script1>();

to

usingScript1 = GetComponent<Script1>();

The latter line of code sets the variable usingScript1 so that you can use it in your code. The former simply calls a function without doing anything with the information it returns.

EDIT: GetComponent() will only work is the two scripts are attatched to the same gameobject. Otherwise, you can use FindObjectOfType().

Upvotes: 1

Related Questions