Hi!
Im having problems with a c# script right now. The Update function simply won’t work. No matter what code i put in it, it won’t work. I removed all of my code and replaced it with a Debug.Log just to test, but nothing happens.
void Update()
{
Debug.Log("abc");
}
The code won’t run. The console is empty when i hit play. It works perfectly if i copy the code into another script in my project. The rest of the code in the script works as well. Is this supposed to be possible? What can possibly cause something like this?
Is the script on an object in the scene? Is the script active? Is the GameObject active? Create an empty gameobject, throw the script on it. Does it run?
@PraetorBlue is super fast!
1 Like
This is the whole script. I use it for saving the amount of coins collected as well as the current highscore. Everything works as intended except the Update function. Note that i used the Update function for updating highscores, but replaced the code with a Debug.Log for easier testing. All the other scripts work fine. The class name matches the script name, it is attached to an enabled gameObject and the script runs. Everything runs except Update().
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveScript : MonoBehaviour
{
public int coins;
public int highScore;
void Awake()
{
LoadGame();
}
void Start()
{
DontDestroyOnLoad(transform.gameObject);
}
void Update()
{
Debug.Log("abc");
}
public void SaveGame()
{
PlayerPrefs.SetInt("Coins", coins);
PlayerPrefs.SetInt("Highscore", highScore);
PlayerPrefs.Save();
Debug.Log("Saved");
}
void LoadGame()
{
if (PlayerPrefs.HasKey("Coins"))
{
coins = PlayerPrefs.GetInt("Coins");
highScore = PlayerPrefs.GetInt("Highscore");
Debug.Log("Loaded");
}
else
Debug.LogError("No save data found");
}
}
Solved the problem! Just a stupid noob mistake. Since i use DontDestroyOnLoad(), i only have the gameObject and the script in one scene, my menu scene. I was editing another scene when i started playing, so of course the script wasnt active. The rest of the script outside of the update function is only used for saving, so i did not notice that it didnt work either. Thanks!
2 Likes
You can actually do away with dropping this into the scene and just have it come into existence when you access it. That pattern is called a singleton and in Unity, here are some super-simple Singleton examples to take and modify:
Simple Unity3D Singleton (no predefined data): <— probably the one you want
https://pastebin.com/SuvBWCpJ
Unity3D Singleton with Prefab used for predefined data:
https://pastebin.com/cv1vtS6G
These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
If you did that then you would access it with:
SaveScript.Instance.SaveGame();
The instant you attempt to use Instance that script will be created, and you never drag it into any scene… once created it just hangs around in your DoNotDestroy list.
1 Like