2
votes

I am trying to get data from an int variable in Unity using C# code. Below is the C# code I am using to get the int.

using UnityEngine;
using System.Collections;

public class endGameMessage : MonoBehaviour {
public static int score2;

void Start () {
    GameObject thePlayer = GameObject.FindWithTag("Player");
    gameScript game = thePlayer.GetComponent<gameScript>();
    score2 = game.score;
}

// Update is called once per frame
void Update () {

    Debug.Log (score2);

}
}

Below is the code from the other script I am trying to pull the data from.

using UnityEngine;
using System.Collections;

public class gameScript : MonoBehaviour {
//score
public int score = 0;
void OnTriggerEnter(Collider other) {
    if(other.gameObject.tag =="hammer"){
        GameObject.FindGameObjectWithTag("pickUpMessage").guiText.text = ("Picked Up A Hammer");    

        Destroy(other.gameObject);
        Debug.Log("collision detected hammer");
        audio.PlayOneShot(gotHit);
        score = score+10;
    }
     }
}

I can get the the int value to come across to the other script but its always 0 even if the int was meant to be 10.

My question is how would i keep the value across the scripts? Any help is appreciated.

3

3 Answers

1
votes

try this

public static int score2
{
    get
    {
        return GameObject.FindWithTag("Player").GetComponent<gameScript>().score;
    }
}
1
votes

You have a lot of possibilities.

The first one is to set your Score as a static argument for you gameScript.

  • So you can access it anywhere just like that :

    int myScore = gameScript.Score ;
    
  • And the declaration should be :

    public static int score;
    

The second possibilities is far better if you want to save a lot of differents values from differents script. In this case, you need to define a gameContext singleton.

If you don't know what is this, you should take a look at singleton in C# : [https://msdn.microsoft.com/en-us/library/ff650316.aspx]

Singleton will allow you to have a single instance of your gameContext. In your case, your singleton will have a Score attribute. And you will be able to get the value from any scene and any scripts.

This is the best way so far.

0
votes

score2 is read once at start and then never again. int is an integral type in C# and thus passed by value i.e. it receives a copy. There several ways to solve this problem.

The easiest solution is to access the gameScript.score directly - it provides read/write access to everyone anyway. To encapsulate it you may choose to define a property.

A better way could be to define a new class GameStatus which holds all relevant things. This can be implemented as singleton for example.