(SOLVED) Doubt about how to get a string variable from another script

Hello everyone!
Im new on Unity and I’m trying to learn while I do my graduation project. My doubt is how use variables of a script inside other one.

I have one script that stores the tag of an object when I click on it. Then, other script has to know that and use this string variable to do something. I did this:

switch (escolha) {

        case "Lata":

            lata.GetComponent<Renderer> ().enabled = true;
            garrafa.GetComponent<Renderer> ().enabled = false;
            pet.GetComponent<Renderer> ().enabled = false;
            selecao = "lata";
            break;

My Variable “selecao” receive one string and its called in the other script by this way:

public class Controleprojetil : MonoBehaviour
{
    private Latinha scriptlatinha; //script name
    private string selecao2; //other variable to store the other one coming from the other script

 void Start()
 {
        scriptlatinha = GameObject.FindObjectOfType <Latinha> ();
}

 void Update()
    {
        selecao2 = scriptlatinha.selecao;
}

 void OnTriggerEnter2D(Collider2D other)
    {
        Debug.LogError (selecao2);
        if (other.GetComponent<CapsuleCollider2D>().tag == "lMetal" && scriptlatinha.selecao == "lata") {...

What am I doing wrong? The result of “Debug.LogError (selecao2)” is always OBJECT and not “lata” as was expected.

Thank you for help!

is selecao a public variable? Only then can you grab it.

1 Like

Yes, It is.

scriptlatinha = GameObject.FindObjectOfType ();
This is the issue, you find the object and not the actual script. U need to grab it with GetComponent();
Good luck

1 Like

Also, to note, update may not be the best place to refresh your variable. Do you really need to set it’s value every frame?

And please use code tags when posting code Using code tags properly

2 Likes

I Will try this. But I think I already did It before. I Will post again when its done.
Tks

This is incorrect. When you call FindObjectOfType(), it returns you a reference to the actual Latinha component found (or null if none can be found). If it did not, then your assignment to scriptlatinha would not even compile.

I can’t tell from what you’ve posted why it’s not working. But I notice that you don’t actually need to store the string in your update method, just to check it in OnTriggerEnter2D… you could check it directly, i.e., just reference scriptlatinha.selecao in your OnTriggerEnter2D event (and delete the selecao2 field from your class).

1 Like

Sorry for not using code tags. I didn’t know how to use it.

I put the variable in the Update Method to instantly know when the “selecao” get a newer value. As I have said, I m new on Unity. Thank you for helping me!

That was I thought. I saw some video tutorials and they used this method. I ll try your tip and the one of Basen1. Lets see if I can do some progress! Thanks a lot!

JoeStrout, when I tried your tip, I got this message: “NullReferenceException: Object reference not set to an instance of an object”.

Basen1, I have tried your tip too. Same message above.

Guys. I found one more clue about this issue. SELECAO is a string variable. Its coming with " " (empty) from the other script. Thats why my condition doesnt work.
Any ideas about why is this happening?

Please post the updated (simpler) version of the code.

This error message means that you’re using some object reference (probably scriptlatinha) which is null, i.e., it doesn’t refer to any object at all. That could be because FindObjectOfType returned null, or because the FindObjectOfType never actually happened.

Use Debug.Log to examine variables (e.g., right after you call FindObjectOfType). Never assume something like Find is going to work — verify that it works, by actually checking the result.

Guys. I found one more clue about this issue. SELECAO is a string variable. Its coming with " " (empty) from the other script. Thats why my condition doesnt work.
Any ideas about why is this happening?

Please post the updated code, and we might be able to tell you.

Right.

In the start method:

void Start()
    {
        latinha = GameObject.Find ("Latinha").GetComponent<Latinha> ();

        if (latinha != null){
        
            Debug.LogError ("Objeto Latinha foi encontrado");
        }
}

In the OnTriggerEnter2D method:

    void OnTriggerEnter2D(Collider2D other)
    {
        if (latinha.selecao != null) {
            Debug.LogError ("Selecao found something");
            Debug.LogError (latinha.selecao); //Shows the content of selecao. Usually " " (empty, different from null).
        }
        if (other.GetComponent<CapsuleCollider2D>().tag == "lVidro" && latinha.selecao == "garrafa" ) {
            Text score = GameObject.Find ("/Canvas/score").GetComponent<Text> ();
            score.text = (int.Parse (score.text) + 100).ToString ();

            Acerto ();
        }

What now?
Tks.

OK, thanks. The code you’ve posted looks correct. If the selecao property is empty-string, then it’s empty-string… the explanation for that would be in the Latinha script, not in this one.

If it’s like your original post, then you should be assigning a value to selecao in certain cases. But there are lots of ways to mess that up — for example, a common newbie mistake is to declare a local variable with the same name as the class field. So you think you’re assigning to the field, but really you’re only assigning to the local variable.

If you post your entire Latinha script, then we can help you look for errors like that.

Here it is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Latinha : MonoBehaviour {
    public float Timer;
    public bool click;
    public bool click1;
    private string escolha;    
    private GameObject lata, garrafa, pet;
    public string selecao;


    void Start () {

        //Encontra e define os objetos para seleção
        lata = GameObject.FindGameObjectWithTag ("sbl_lata");
        garrafa = GameObject.FindGameObjectWithTag ("sbl_garrafa");
        pet = GameObject.FindGameObjectWithTag ("sbl_pet");

        //Esconde todos os objetos de seleção
        lata.GetComponent<Renderer> ().enabled = false;
        garrafa.GetComponent<Renderer> ().enabled = false;
        pet.GetComponent<Renderer> ().enabled = false;

        click = false; //Mostra para o script que nenhum objeto foi clicado
        Timer = 0; // Zera o cronômetro
        click1 = false; //Mostra que o primeiro click ainda não foi dado sobre o objeto
    }


    void Update (){    

        // Se o objeto foi clicado e o tempo é inferior a 0,5 segundos
        if (click && Timer < 0.5) {
            
            if (click1) { //Se é a primeira vez que se clica sobre o objeto
                
                transform.Rotate (0, 0, 27); //Rotaciona o objeto para a direita (27°)
                MostraObj (); //Chama o método Escolha, que define qual objeto será mostrado na seleção


            } else { //Se é a segunda vez que se clica sobre o objeto
                
                transform.Rotate (0, 0, -27);//Rotaciona o objeto para a esquerda (27°)
                escolha = "nada"; //Define que a string escolha é "nada"
                MostraObj (); //Chama o método Escolha

            }

            Timer += Time.deltaTime; //Acrescenta tempo ao Timer para parar a execução



        } else { //Quando o tempo chega a 0,5 e nenhum novo objeto é clicado
            
            click = false; //Click recebe falso
            Timer = 0; //Tempo é zerado
            escolha = null; //A escolha é limpa

        }

    }
        
    void OnMouseDown(){ //Método que indica o que ser feito ao click do mouse sobre objeto

        escolha = gameObject.tag; // A variável escolha recebe a tag do objeto clicado
        click = true; //Identifica o click na condição do médoto Update, permitindo o giro do objeto.
        /*Define a variável click1 para false ou true dependendo da condição anterior, fazendo o objeto
         mudar de direção na rotação do método update*/

        if (click1) {
            click1 = false;
        } else {
            click1 = true;
        }

    }

    public void MostraObj(){ //Método responsável por definir qual objeto deve ser mostrado na tela de seleção


        
        switch (escolha) { //Condição passada pelo método OnMouseDown e Update

        case "Lata": //Se o objeto clicado tinha a tag "Lata", mostra somente o símbolo Lata

            lata.GetComponent<Renderer> ().enabled = true;
            garrafa.GetComponent<Renderer> ().enabled = false;
            pet.GetComponent<Renderer> ().enabled = false;
            selecao = "lata";
            Debug.LogError (selecao);
            break;

        case "Garrafa": //Se o objeto clicado tinha a tag "Garrafa", mostra somente o símbolo Garrafa

            lata.GetComponent<Renderer> ().enabled = false;
            garrafa.GetComponent<Renderer> ().enabled = true;
            pet.GetComponent<Renderer> ().enabled = false;
            selecao = "garrafa";
            Debug.LogError (selecao);
            break;

        case "Pet": //Se o objeto clicado tinha a tag "Pet", mostra somente o símbolo Pet

            lata.GetComponent<Renderer> ().enabled = false;
            garrafa.GetComponent<Renderer> ().enabled = false;
            pet.GetComponent<Renderer> ().enabled = true;
            selecao = "pet";
            Debug.LogError (selecao);
            break;

        case "nada": //Se a tag retornou "nada", esconde todos os símbolos

            lata.GetComponent<Renderer> ().enabled = false;
            garrafa.GetComponent<Renderer> ().enabled = false;
            pet.GetComponent<Renderer> ().enabled = false;    
            Debug.LogError (selecao);
            selecao = null;
            break;


    }

        
}
}

OK, this looks good. I see you’ve put LogError calls everywhere you assign to selecao (though in the “nada” case, you’re doing it before the assignment — you should move that one down).

So do these LogErrors messages appear when you expect them to? And afterwards, do you see what you expect from the other script?

If not, then check whether have more than one Latinha object in your scene. That might be a source of confusion.

When you say “If not, then check whether have more than one Latinha object in your scene. That might be a source of confusion”, you mean a gameobject with an attached Script Latinha on it? Because I have more than one in this case. I created a “gameobjetc” Latinha and replicate it, changing his tag.

Thank you for the support.

1 Like

Also, the “Debug.LogErrors” show the content of the variable “selecao” in each of the cases.