I am putting myself through learning Unity atm and I got an issue. I have a class GameVariablesController. That is only a C# Script. This is supposed to hold all game variables that need to be saved. Now I want to access them. However, I am not sure how to do this. In Game Maker Studio, I would make an Object, add it to the scene and access this one via the game object list. So I tried to do the same in Unity.
For finding the GameObject, I need to search for it and GameObject.Find(); returns me the object. However, it does not contain the definitions for the functions the script is holding. So my question is, how do I access the instance of that script? I am not quite sure how this works in Unity.
If there’s only one instance of that script in the scene, you can simply use
GameVariablesController gvc = FindObjectOfType<GameVariablesController>();
It saves you from finding the bearer.
The component has to be on a game object in the scene though.
To add to the answer @UnityCoach has given, I am using this singleton to solve the issueusing
System.Collections;
using System.Collections.Generic;
using UnityEngine;
//---------------------------------------------
public class GameVariablesController
//---------------------------------------------
{
//---------------------------------------------
// Private Members
//---------------------------------------------
private static GameVariablesController instance = null;
private static readonly object padlock = new Object();
//---------------------------------------------
// Public Members
//---------------------------------------------
public float playerShipMaxSpeed {get;set;}
public float playerBulletMaxSpeed {get; set;}
//---------------------------------------------
GameVariablesController()
//---------------------------------------------
{
playerShipMaxSpeed = 40;
playerBulletMaxSpeed = 900;
}
//---------------------------------------------
public static GameVariablesController Instance
//---------------------------------------------
{
get
{
lock(padlock)
{
if ( instance == null )
{
instance = new GameVariablesController();
}
return instance;
}
}
}
}