Tutorial: How to access variable from other class in Unity

I have dealt with this problem very often.

How to get variables from other Class in Unity? For example I’ve got one Class with public Variables and i want to get the same value of the Variable in other Class.

For Example it could be a Class which adds points to overall Score. But in other Class i show it using Unity UI System as Text.

Here is the Class with Variable which is calling the Function in other Class.

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

public class Score : MonoBehaviour {

  public GameObject scoreScript;
  // Use this for initialization

  public void OnTriggerEnter2D(Collider2D node)
  {
    if (node.gameObject.tag == "Apple") {
      Destroy (node.gameObject);
      ScoreMenager scorePointsScript =  scoreScript.GetComponent<ScoreMenager>();
      scorePointsScript.AddScore ();

    }
  }
}

 

And here is the Class which contains the Function where the variable points gets incremented.

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

public class ScoreMenager : MonoBehaviour {
  public int points;


  Text text;

  void Awake ()
  {
    text = GetComponent<Text> ();

  }
  // Use this for initialization
  void Start () {
  }

  public void AddScore()
  {
    points++;
  }
  // Update is called once per frame
  void Update () {
    

    text.text = "Score: " + points;
  }
}

 

Don’t Forget to Add The “Score” Script to your character! And the same for ScoreMenager, which needs to be added to the UI Element.

And also don’t forget to Create the Text as GUI

Also important is the fact, that you need to change the “Tag” of your element which will be destroyed. After it increases the Score Points value.

Component > UI > Text

 

Other tutorials in the series:

How to make the objects fall in Unity

Making Objects Fall Random On The Screen in Unity

How to Speed Up (Increase Speed) Time in Unity

How to create a simple countdown Timer in Unity

How to make the objects fall in Unity

There are a lot of ways how to make the objects fall in Unity. In our game we are using two of them.

Why did the left timer hit the ground first? After all the red watch was a little higher than the blue one. Thanks to Physics! And artificial Gravitational pull.

While the left watch was taking on the speed and falling faster in every millisecond (for example like cars do) the right one had a steady linear falling speed. You can use this in a lot of ways.

Why don’t we stick with one falling type? Because we wanted to differentiate the two falling types for different objects.

If you want to use the right way of objects falling (Blue Timer) you can use this script below and assign it to the object.

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

public class TimerFall : MonoBehaviour {

  public float fallSpeed = 40.0f;      //How fast should the object fall

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

      transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
  }
}

As you see. It’s not much. In fact we need only to write two lines of code. Variable initialization which is responsible for the speed of falling and the transform.Translate function. What does the function do? It just changes the position of an object in the Scene. That’s all.

In the left example (Red Timer) we don’t any code at all!

You just need to use build-in function called Rigidbody 2D. On the object “Add Component” => Physics 2D => Rigidbody 2D

What kind of numbers (variables) do i need to put there to make the physics work? It depends on what do you want to achieve. I am focusing most of the time on “Mass” and Gravity Scale. Sometimes i change the Linear Drag and Angular drag. But not so often.

Here are the variables used in the example above:

Well that’s all you need to know. Thanks for reading.

Making Objects Fall Random On The Screen in Unity

How to spawn object on the screen in Unity Randomly?

I am currently developing with a friend o mine a game. It’s called Badger Adventures. It’s a very simple game in which you are collecting Apples with an Badger.

So… how do you spawn apples randomly?

Actually, if you are an experienced user than you just need to check out the Random.range function which is built in Unity3d Library.

 

Otherwise check out my Script. It’s called AppleSpawn and well… it is spawning Apples.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AppleSpawn : MonoBehaviour {

  public GameObject apple;			// Apple Object in Scene (Sprite)
  public GameObject badApple;			// Bad Apple Object in Scene (Sprite)

  public float spawnTime = 2f;            // How long between each spawn.
  public float fallSpeed = 40.0f;		//The speed of falling Apples

  private float timer = 0; //counting timer, reset after calling SpawnRandom() function
  private int randomNumber; 			//variable for storage of an random Number
  
  void Update () {

    timer += Time.deltaTime;   // Timer Counter
    if(timer>spawnTime){
      SpawnRandom(); 			//Calling method SpawnRandom()
      timer = 0;				//Reseting timer to 0
    }

  }

  public void SpawnRandom()
  {
  
      //Creating random Vector3 position
    Vector3 screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(600 ,Screen.height), Camera.main.farClipPlane/2));

    //Instantiation of the Apple Object
    Instantiate(apple,screenPosition,Quaternion.identity);
  }

}

In the update function there is an if statement because i wanted to restrict the number of spawned Apples. If i want to create more apples i can change the variable in the public function from 2 to 0.2. For the time counting i used Time.deltaTime because this function is frame rate independent.

SpawnRandom() method is creating an random Vector3 value on the top of the screen depending on the Screen Size (Camera) Width and Height.

If we wanted for example to place the spawned elements little lower on the screen we can change the number from 600 to 400. In your example the variable can be a little different depending on the screen size you are developing.

Instatiate just spawns the object on the scene.

That’s all. Thanks for Reading.