Calling a function from another script? Not WORKING?!
I'm trying to call a function from another script that is in another GameObject in another scene. This gameobject cant be DontDestroyOnLoad();
I know that this question has been asked before but every time i look it either uses DontDestroyOnLoad or the gameobject is in the same scene or people just reference an article that has been removed.
So here is my code. Script 1 referencing the function. using UnityEngine; using System.Collections;
public class StartMinerPrefs : MonoBehaviour {
void Awake()
{
SaveManager.savemanager.CreateFile ();
}
}
The second script that contains the function
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class SaveManager : MonoBehaviour {
public static SaveManager savemanager;
//Need functions that dont close stream but just access the file to save other stuff.
public void CreateFile()
{
if (!File.Exists (Application.persistentDataPath + "/saveFile.data")) {
FileStream fstream = File.Create (Application.persistentDataPath + "/saveFile.data");
} else {
if (File.Exists(Application.persistentDataPath + "/saveFile.data"))
{
BinaryFormatter binary = new BinaryFormatter();
FileStream fstream = File.Open(Application.persistentDataPath + "/saveFile.data", FileMode.Open);
VarSaveManager saver = (VarSaveManager)binary.Deserialize (fstream);
fstream.Close ();
DuckCounter.duckcounter.gold = saver.gold;
//ALL OTHER INFO//
}
}
}
public void Save()
{
BinaryFormatter binary = new BinaryFormatter ();
FileStream fstream = File.Open (Application.persistentDataPath + "/saveFile.data", FileMode.Open);
VarSaveManager saver = new VarSaveManager ();
saver.gold = DuckCounter.duckcounter.gold;
//ALL OTHER INFO//
binary.Serialize(fstream, saver);
fstream.Close ();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/saveFile.data"))
{
BinaryFormatter binary = new BinaryFormatter();
FileStream fstream = File.Open(Application.persistentDataPath + "/saveFile.data", FileMode.Open);
VarSaveManager saver = (VarSaveManager)binary.Deserialize (fstream);
fstream.Close ();
DuckCounter.duckcounter.gold = saver.gold;
//ALL OTHER INFO//
}
}
[Serializable]
class VarSaveManager
{
public int gold;
//ALL OTHER INFO//
}
(THE FUNCTION IS CALLED CREATEFILE)
Answer by LTK · Aug 22, 2016 at 08:45 AM
saveManager is null You need instance this.
public class SaveManager : MonoBehaviour {
public static SaveManager savemanager;
void Awake(){
if(saveManager != null)
saveManager = this;
}
}
Answer by aditya · Aug 22, 2016 at 07:51 AM
Tag your gameobject, that holds SaveManager
script on it, to something like SM_Script
and then simply call GetComponent in StartMinerPrefs
....
public class StartMinerPrefs : MonoBehaviour {
void Awake()
{
Gameobject.FindObjectWithTag("SM_Script").GetComponent<SaveManager>.savemanger.CreateFile ();
}