Ways to Unity 9: Global variables or variable sharing between scripts
Purpose
Communication, communication, guys.
We need communication to build large software.
Structure
For unity, the variable sharing is more like the static member definition.
You make a public variable, then you get that variable by reference to the script it stores.
Let’s assume you have a PlayerController
script attached to an object called Player
.
You want to get a variable isGameOver
from any other scripts.
The Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLeft : MonoBehaviour
{
private PlayerController playerController;
void Start()
{
playerController = GameObject.Find("Player").GetComponent<PlayerController>();
}
void Update()
{
if (playerController.isGaveOver == false) {
// If game is not over, we do stuffs as usual
}
}
}
The Writer
https://yingshaoxo.blogspot.com/2020/12/ways-to-unity-9-global-variables-or.html