Good Day! I have this code but I have an error, for example (I set two players me, and 1 computer). I take the first turn, and the dice respawn with a value of 4 (just an example), the game piece then move from 1st to 4th tile when I touch the screen, when computer turns, it also move from 1st to 4th tile (because I set the result to 4 just an example). Now its my turn again, the dice never respawn and it doesn't wait to touch the screen if (Input.GetMouseButtonDown(0)) and move again by 4...
public class singlePlay : MonoBehaviour {
//Player
public GameObject[] playerprefab;
//Player Clone
public GameObject[] playerprefabC;
//Game Cards and Dice
public GameObject[] situationCard;
public GameObject dice;
int diceresult;
//Game Cards and Dice clone
public GameObject diceclone;
public int currentPlayer;
public int compPlayer;
public int playerTurn;
public string compPlayerstring;
public string playerTurnstring;
//GUI Boolean
bool play = false;
//Game Boolean
bool pieces = false;
bool giveturn = false;
bool myturn = false;
bool diceSpawn = false;
bool moving = false;
bool routine = false;
bool checking = false;
bool compturn = false;
//icon1
public GameObject[] icon;
//population
int[] population = new int[3];
//Tile
public GameObject[] Tile;
int[] playerTile = new int[3]; //current location
int[] playerTileUp = new int [3]; // updated location after dice roll
bool endTurn = false;
void Update ()
{
if (giveturn == true) {
int h = 0;
Giveturn(h);
giveturn = false;
}
if (play == true) {
if (pieces == true){
SpawnPlayer();
pieces = false;
}
if (myturn == true){
compturn = false;
if(diceSpawn == true) {
dice.transform.position = new Vector3(0,0,-1);
diceclone = Instantiate(dice, dice.transform.position, Quaternion.identity) as GameObject;
diceSpawn = false;
}
if (Input.GetMouseButtonDown(0))
{
Debug.Log("click");
diceresult = 4;
Destroy(diceclone);
moving = true;
Updateposition(diceresult);
}
}
else
{
Debug.Log("comp");
myturn = false;
diceresult = 4;
moving = true;
Updateposition(diceresult);
}
}
}
void Giveturn(int k)
{
Debug.Log("" + k);
currentPlayer = k;
if (k == playerTurn) {
Debug.Log("Yes");
compturn = false;
myturn = true;
diceSpawn = true;
moving = false;
}
else
{
Debug.Log("No");
compturn = true;
myturn = false;
moving = false;
}
}
void Updateposition(int diceresult)
{
if (moving == true) {
playerTileUp[currentPlayer] = playerTile[currentPlayer] + diceresult;
Debug.Log("" + playerTileUp[currentPlayer]+ " " +currentPlayer);
routine = true;
StartCoroutine(MyMethod());
}
moving = false;
}
IEnumerator MyMethod()
{
if (routine == true) {
if (myturn == true) {
compturn = false;
}
else
{
myturn = false;
}
int f = playerTile[currentPlayer] + 1;
Debug.Log(" " + currentPlayer );
while (f <= playerTileUp[currentPlayer]) {
Debug.Log("waiting");
yield return new WaitForSeconds(1);
Debug.Log(" " + Tile[f]);
playerprefabC[currentPlayer].transform.position = Tile[f].transform.position;
Debug.Log(" " + currentPlayer);
f++;
}
checking = true;
TrapCheck();
}
routine = false;
}
void TrapCheck()
{
if (checking == true) {
if (playerTileUp[currentPlayer] == 8) {
Debug.Log("Trap spawning");
Instantiate(situationCard[0], situationCard[0].transform.position, Quaternion.identity);
population[currentPlayer] = population[currentPlayer] -1;
}
playerTile[currentPlayer] = playerTileUp[currentPlayer];
Endturn();
myturn = false;
compturn = false;
checking = false;
}
}
void Endturn()
{
currentPlayer++;
Debug.Log(" " + currentPlayer);
if (currentPlayer > compPlayer) {
currentPlayer = 0;
}
Giveturn(currentPlayer);
}
}
There are few things that I could see wrong there already. First while the coroutine is running, it seems you are not preventing the update from running since play remains true. In TrapCheck, you call EndTurn which call GiveTurn and sets myTurn (true) and compTurn (false) booleans. But those two are reset in TrapCheck, myTurn is set back to false. You need to rethink the logic of your class.
A solution would be to use delegate. This would remove many of your boolean that you set and reset. Here is a basic idea:
Action currentUpdate;
bool playerTurn = true;
void Start(){
SetTurn();
}
void Update(){
if(currentUpdate != null)currentUpdate();
}
void SetTurn(){
// Prepare initial setting for moving
if(playerTurn == true){ currentUpdate = PlayerTurn; }
else{ currentUpdate = CompTurn; }
playerTurn = !playerTurn;
}
void PlayerTurn(){
// Check input
// Get dice value
currentUpdate = Move;
}
void CompTurn(){
// Get dice value
currentUpdate = Move;
}
void Move(){
if(position != target){
}else{
SetTurn();
}
}
This is fairly simplified but once you get the thing about delegate (maybe you already know), this will make it all so much more flexible.
Related
Guys When I gave it something tagged with pizza first coroutine doesn't stop How Can I stop it?
Please help me guys I couldn't find the way. What should I do? Btw I am new sorry for bad posting:/
I'm trying to make a pizza restaurant game. So customer will sit then waitforpizza coroutine will start if we give tag with pizza waitforpizza coroutine should start then eatpizza will start but my waitforpizza doesn't stop.
IEnumerator EAT, PAY, WAIT;
private void Start()
{
EAT = EatPizza();
WAIT = WaitForPizza();
PAY = WaitForTheCase();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pizza"))
{
canEat = true;
}
if (other.gameObject.CompareTag("Out"))
{
Destroy(this.gameObject);
}
}
void Update()
{
if (isEating)
{
if (Vector3.Distance(transform.position, agent.destination) <= 1f)
{
anim.SetTrigger("sit");
isEating = false;
}
}
if (!isEating && !isPaying && !isOut && !canEat)
{
StartCoroutine(WaitForPizza());
}
if (!isEating && !isPaying && !isOut && canEat)
{
StopCoroutine(WAIT);
StartCoroutine(EatPizza());
}
if (isPaying)
{
isEating = false;
anim.SetTrigger("walk");
agent.destination = checkoutTarget.position;
if (Vector3.Distance(transform.position, agent.destination) <= 1f)
{
anim.SetTrigger("wait");
if (ifCashier)
{
//throw money
isPaying = false;
isOut = true;
}
if (!ifCashier)
{
StartCoroutine(WaitForTheCase());
}
}
}
if (isOut)
{
anim.SetTrigger("walk");
isEating = false;
isPaying = false;
agent.destination = outTarget.position;
}
if (canEat)
{
StopCoroutine(WAIT);
}
}
IEnumerator WaitForTheCase()
{
anim.SetTrigger("wait");
yield return new WaitForSeconds(randomFloatWait);
angry.SetActive(true);
isEating = false;
isPaying = false;
isOut = true;
}
IEnumerator EatPizza()
{
angry.SetActive(false);
StopCoroutine(WaitForPizza());
happy.SetActive(true);
yield return new WaitForSeconds(randomFloatWait);
happy.SetActive(false);
isEating = false;
isPaying = true;
isOut = false;
}
IEnumerator WaitForPizza()
{
while (!canEat)
{
yield return new WaitForSeconds(randomFloatWait);
angry.SetActive(true);
isEating = false;
isPaying = false;
isOut = true;
}
}
First, define WAIT as Coroutine then when you want to start waiting use WAIT = StartCoroutine(WaitForPizza()); and when you want to finish it use StopCoroutine(WAIT);.
Hello I'm trying to make a gun system and everything is working except Switching gun that stored in my GameObject array playerGuns, it always stores it on 0
and when I press another key it disabled every object that created.
I want to make it so when you will press 1-4 key on your keyboard it will switch
between the gun that stored on playerGuns and disables the other gun, you ware holding.
I couldn't find why the problem is happening so please help.
public GameObject Player;
public GameObject Showui;
public RectTransform Uirect;
public Material greenQu, blueQu;
public GameObject nameObject;
public GameObject rearityObject;
public GameObject dmgObject;
public GameObject levelObject;
private Text nameText;
private Text rearityText;
private Text dmgText;
private Text levelText;
private Image infoImage;
private Gunsystem gunScript;
private string gunName;
private int index = 0, index2 = 0;
private bool pressed = false, Show = false;
public Gun[] Inventory = new Gun[4];
public GameObject[] playerGuns = new GameObject[4] { null, null, null, null};
public int keyPress = 0;
void Start () {
gunScript = Player.GetComponent<Gunsystem>();
infoImage = Showui.GetComponent<Image>();
//Get text from objects
nameText = nameObject.GetComponent<Text>();
rearityText = rearityObject.GetComponent<Text>();
dmgText = dmgObject.GetComponent<Text>();
levelText = levelObject.GetComponent<Text>();
gunName = gameObject.name;
Debug.Log(gunName);
}
private void Update()
{
KeyCode pickup = KeyCode.E;
KeyCode key1 = KeyCode.Alpha1;
KeyCode key2 = KeyCode.Alpha2;
KeyCode key3 = KeyCode.Alpha3;
KeyCode key4 = KeyCode.Alpha4;
//Handling inventory keys
if (Input.GetKeyDown(key1))
{
keyPress = 0;
if (playerGuns[0] != null && !playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(true);
}
if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key2))
{
keyPress = 1;
if (playerGuns[1] != null && !playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}else if (Input.GetKeyDown(key3))
{
keyPress = 2;
if (playerGuns[2] != null && !playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[3] != null && playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(false);
}
}
else if (Input.GetKeyDown(key4))
{
keyPress = 3;
if (playerGuns[3] != null && !playerGuns[3].activeInHierarchy)
{
playerGuns[3].SetActive(true);
}
if (playerGuns[0] != null && playerGuns[0].activeInHierarchy)
{
playerGuns[0].SetActive(false);
}
else if (playerGuns[1] != null && playerGuns[1].activeInHierarchy)
{
playerGuns[1].SetActive(false);
}
else if (playerGuns[2] != null && playerGuns[2].activeInHierarchy)
{
playerGuns[2].SetActive(false);
}
}
//Pick the gun when key pressed and store it
if (Input.GetKeyDown(pickup) && Show == true)
{
foreach (Gun item in gunScript.gunList)
{
if (index2 == Convert.ToInt32(gunName))
{
if (item.gunType == "Normal")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Change rigidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
else if (item.gunType == "Stride")
{
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
//Set rgidbody and disable collider
playerGuns[keyPress].GetComponent<Rigidbody>().useGravity = false;
playerGuns[keyPress].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
playerGuns[keyPress].GetComponent<MeshCollider>().enabled = false;
//Store gundata in inventory
item.Named = false;
Inventory[keyPress] = item;
pressed = true;
}
}
index2++;
}
index2 = 0;
}
}
private void OnMouseEnter()
{
Vector3 Pos = Camera.main.WorldToScreenPoint(transform.position);
Showui.transform.position = Pos;
Showui.transform.position += new Vector3(0, 90f, 0.5f);
gunScript.updateGuns = true;
Show = true;
foreach (Gun item in gunScript.gunList)
{
if (index == Convert.ToInt32(gunName))
{
if(item.gunType == "Normal")
{
infoImage.material = greenQu;
}else if (item.gunType == "Stride")
{
infoImage.material = blueQu;
}
LayoutRebuilder.ForceRebuildLayoutImmediate(Uirect);
if(item.Named != false)
Showui.SetActive(true);
nameText.text = "Name: " + item.Name;
rearityText.text = "Rearity: " + item.gunType;
dmgText.text = "Damage: " + Mathf.Round(item.Dmg).ToString();
levelText.text = "Level: " + item.gunLevel.ToString();
//Debug.Log(item.Name);
//Debug.Log(item.gunType);
//Debug.Log(item.Dmg);
//Debug.Log(item.gunLevel);
}
index++;
}
index = 0;
}
private void OnMouseExit()
{
Show = false;
Showui.SetActive(false);
}
I wrote a little script that should handle the activation and the deactivation of your four guns.
Hope It helps,
Alex
public GameObject[] Guns;
void Start(){
for (int i=0; i<3; i++){
if(Guns[i] == null) Debug.LogError("Gun n°" + i +" is null);
}
}
void Update(){
if(Input.GetKeyDown(Input.KeyCode.Alpha1)){
setGunActive(1);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha2)){
setGunActive(2);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha3)){
setGunActive(3);
}
if(Input.GetKeyDown(Input.KeyCode.Alpha4)){
setGunActive(4);
}
}
void setGunActive(int n){
foreach(GameObject g in Guns){
g.setActive(false);
}
Guns[n].setActive(true);
}
When I look at some object and press the button, I need to do something. When I do it for the first time, it works, but then I don't need to press the button again, I can just look at object. But player must look at object and press the button, not only look
private Collider thisCollider;
public int ActionNumber { get; private set; }
void Start ()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1") && DoPlayerLookAtObject())
ActionsList();
}
bool DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
if (isHit && _hit.collider == thisCollider)
return true; // this return true all the time after first interaction with object
else
return false;
}
public bool ActionsList()
{
if (DoPlayerLookAtObject())
switch (thisCollider.name)
{
case "barthender": ActionNumber = 1; return true;
case "doorToStreet": ActionNumber = 2; return true;
default: Debug.Log("Error: Out of range"); break;
}
return false;
}
How I use it:
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
if (onMousePressCasinoBarthender.ActionNumber == 1 &&
onMousePressCasinoBarthender.ActionsList())
// do something
if (onMousePressCasinoDoorToStreet.ActionNumber == 2 &&
onMousePressCasinoDoorToStreet.ActionsList())
// do something
Edit 1 Ignoring player's collider. Video from the game
Okay so basically you're settings you ActionNumber to ( let's say ) 1 and it stays at this value.
To fix this up you would have to set time based reset of that value or just use Raycast all the time in Update ( or LateUpdate ).
Another way would be to make use of event driven programming principles and just fire the event whenever your conditions are met and forget about setting some values.
Making it simple enough :
private Collider thisCollider;
public event EventHandler<MeEventArgs> OnAction;
void Start()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
EventHandler<MeEventArgs> handler = OnAction;
int actionIndex = DoPlayerLookAtObject();
if ( handler != null && actionIndex >= 0)
{
handler(this, new MeEventArgs(actionIndex));
}
}
}
int DoPlayerLookAtObject()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
//if (isHit && _hit.collider == thisCollider)
// return true; // this return true all the time after first interaction with object
//else
// return false;
if (isHit && _hit.collider == thisCollider)
return ActionList();
return -1;
}
public int ActionsList()
{
int result = -1;
switch (thisCollider.name)
{
case "barthender": result = 1; break;
case "doorToStreet": result = 2; break;
default: Debug.Log("Error: Out of range"); break;
}
return result;
}
Now create MeEventArgs :
public class MeEventArgs : EventArgs
{
public readonly int Action;
public MeEventArgs(int actionIndex) : base()
{
Action = actionIndex;
}
}
And to use this in code :
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
void Start()
{
onMousePressCasinoBarthender.OnAction += MeAction;
onMousePressCasinoDoorToStreet.OnAction += MeAction;
}
void MeAction(object sender, MeEventArgs e)
{
if(e.Action == 1)
{
// do something
}
else if (e.Action == 2)
{
// do something else.
}
}
public class green : MonoBehaviour
{
private AudioSource source;
public AudioClip sound;
static int result = 0;
// Use this for initialization
void Start()
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
Debug.Log("a");
}
IEnumerator RoutineCheckInputAfter3Minutes()
{
System.Random ran = new System.Random();
int timeToWait = ran.Next(1, 50) * 1000;
Thread.Sleep(timeToWait);
source = this.gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.loop = true;
source.Play();
System.Random r = new System.Random();
result = r.Next(1, 4);
Debug.Log("d");
yield return new WaitForSeconds(3f * 60f);
gm.life -= 1;
Debug.Log(gm.life + "값");
source.Stop();
Debug.Log("z");
if (gm.life >= 0)
{
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
// Update is called once per frame
public void Update()
{
if (result == 1 && gm.checkeat == true)
{
Debug.Log("e");
gm.life += 1;
Debug.Log("j");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkeat = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
if (result == 2 && gm.checkshit == true)
{
Debug.Log("f");
gm.life += 1;
Debug.Log("o");
Debug.Log(gm.life + "값");
source.Stop();
gm.checkshit = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
else if (result == 3 && gm.checksleep == true)
{
Debug.Log("g");
gm.life += 1;
Debug.Log(gm.life);
Debug.Log(gm.life + "값");
source.Stop();
gm.checksleep = false;
StopCoroutine("RoutineCheckInputAfter3Minutes");
StartCoroutine("RoutineCheckInputAfter3Minutes");
}
}
}
public class gm : MonoBehaviour
{
static public int life = 0;
static public bool checkeat = false;
static public bool checkshit = false;
static public bool checksleep = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void eating(string eat)
{
Debug.Log(life + "값");
checkeat = true;
}
public void shitting(string shit)
{
Debug.Log(life + "값");
checkshit = true;
}
public void sleeping(string sleep)
{
Debug.Log(life + "값");
checksleep = true;
}
}
when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
.when i click a button , program stops for a while and then works... i think it is because of thread or something...
please share your opinion..
Stop using :
Thread.Sleep(timeToWait);
This stalls the entire thread, in this case Unity completely from running.
Since your using routines anyway, use this instead :
yield return new WaitForSeconds(timeToWait);
And change this line :
int timeToWait = ran.Next(1, 50) * 1000;
To this :
int timeToWait = ran.Next(1, 50);
I have the following code which creates a main menu :
public class EscapeGUI : MonoBehaviour {
public GUISkin MySkin;
public bool pauseToggle = false;
public bool showGUI = false;
public bool levelLoaded = false;
static string filePath;
private List<string> list = new List<string>();
private string line;
void Update() {
if (!levelLoaded) {
showGUI = true;
Time.timeScale = 0;
Debug.Log ("NO LEVEL LOADED");
} else {
if (Input.GetKeyDown (KeyCode.Escape)) {
pauseToggle = !pauseToggle;
if (pauseToggle) {
Time.timeScale = 0;
showGUI = true;
} else {
Time.timeScale = 1;
showGUI = false;
}
}
Debug.Log("FILEPATH IS " + filePath);
Debug.Log("LEVEL IS LOADED");
}
}
void OnGUI() {
if (showGUI) {
GUI.skin = MySkin;
GUILayout.BeginArea (new Rect (Screen.width / 4, Screen.height / 4, 400, Screen.width / 2));
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Resume")) {
Time.timeScale = 1;
showGUI = false;
pauseToggle = false;
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Restart")) {
Application.LoadLevel (0);
showGUI = false;
pauseToggle = false;
Time.timeScale = 1;
levelLoaded = true;
Debug.Log ("Game is restarted with this level: " + filePath);
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Load")) {
filePath = EditorUtility.OpenFilePanel("Select JSON file",Application.streamingAssetsPath,"txt");
Debug.Log ("Game is loaded with this level: " + filePath);
StreamReader reader = new StreamReader(filePath);
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
//Debug.Log(line);
}
//Do this as soon as the JSON is checked and found to be OK.
GameObject.Find("Preserved Variables").SendMessage("setFilePath", filePath);
Time.timeScale = 1;
levelLoaded = true;
showGUI = false;
pauseToggle = false;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Quit")) {
Application.Quit();
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
}
}
}
A game is created by importing a JSON file (in the code its just txt for testing, i have not implemented the JSON part yet), in this JSON file the game flow will be described.
So basically when a player clicks load, I want the game to be playable and then when he clicks restart because of the 'Application.LoadLevel (0);' code everythings gets deleted, thus I don't know anymore what the current file (level) it was.
So I created an empty gameobject called 'Preserved Variables' and I put a C# script component in this, the script looks like this:
public class PreservedVariables : MonoBehaviour {
public string filePath;
public static PreservedVariables instance;
void Awake() {
if(instance){
Destroy(this);
} else {
DontDestroyOnLoad(this);
instance = this;
}
}
void setFilePath(string fp) {
filePath = fp;
}
string getFilePath() {
return filePath;
}
}
Now the problem is that when I run this and ingame i click 'load', i select my file and so far everything is good. But then when I click "restart" I get the following 2 problems:
1) the main menu shows me only the 'load' and 'quit' as it is only supposed to show when there is no game loaded (so this only happens at startup), however i think this will be fixed by fixing nr.2 (see below)
2) As soon as i click restart after loading a file, the gameobject 'Preserved Variables' is made again but this time it does not have a script component attached. (the original gameobject has its FilePath updated correctly though).
If I may I would like to ask an extra small question to this, how do I exactly retrieve the filepath variable again from the empty gameobject 'Preserved Variables' so that I can use it in my restart code?