I've looking for info to try to solve my problem and I just can't figure out what it's causing it. Player Prefs seem to work fine in unity editor, but once i make a build for Android or PC they are all gone. I have PlayerPrefs.deleteAll no where in my project.
I have 3 scenes: Menu, Game and GameOver. When I start the Menu scene, I run this script attached to the MainCamera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class prefs : MonoBehaviour
{
public static int bestRecord;
// Start is called before the first frame update
void Start()
{
bestRecord = PlayerPrefs.GetInt("K", 1);
Debug.Log(PlayerPrefs.GetInt("K").ToString());
}
}
When I go into the Game scene, my score is a TextMeshProUGUI that is constantly update by an InvokeRepeating:
public TextMeshProUGUI points;
void Start()
{
stop = false;
InvokeRepeating("subirMetros", 0f, 0.01f);
}
private void subirMetros()
{
if (stop == false)
{
points.SetText(Math.Round(character.transform.position.x, 0) + "");
}
}
//GameOver is called when the player dies
public void GameOver()
{
stop = true;
CancelInvoke("subirMetros");
int finalPoints = Int32.Parse(points.text);
int recordActual = PlayerPrefs.GetInt("K");
if (recordActual < finalPoints)
{
PlayerPrefs.SetInt("K", finalPoints);
}
SceneManager.LoadScene("GameOver");
}
}
Finally, when starting the GameOver scene, I get once again the PlayerPrefs that are supposedly saved before I get to the scene:
public TextMeshProUGUI record;
void Start()
{
record.text = PlayerPrefs.GetInt("K").ToString();
}
The weird thing is that this is working in the unity editor, but not when i build it. I would be very grateful if someone could help me, thanks.
I know this is an old post (forgive me for necro) but it came up as a google search result, and i ran into the same issue.
I had the same issue with playerprefs, i was saving an encrypted file where i used a playerprefs together with a generated key for a hash value. When i saved the game in the editor and ran in the build i couldnt load my save file. This was for windows though. After some debugging and digging I found out that unity saves playerprefs two different places for both editor and application builds:
according to this article
https://virtual-reality-piano.medium.com/solved-where-is-unitys-playerprefs-stored-on-windows-d61d504585e9
Your unity editor saves it at the path: ‘HKEY_CURRENT_USER\SOFTWARE\Unity\UnityEditor\CompanyName\ProjectName’
But, when you build your application, the player prefs are saved at:
'HKEY_CURRENT_USER\SOFTWARE\CompanyName\ProjectName' (where Company name is the name of your company, and project name is the name of your project).
I had to go in and delete the registry files in both places, because say i was saving a Save File with the name DefaultPlayer, then the editor would associate that save with the registry file from the editor. But when i build to an application, the save file would still persist in Application.PersistentPath, but it's registry file would not exist, because it wasn't created yet in the application's registry file.
Sorry for the confusing post and necro, but this is what fixed save file problems for me from editor to application builds. (note this is on windows so dont know if it applies to android as well). Hope it helps anyone else running into the same problem
note you would have to delete both files everytime you test in editor and on builds, or as someone suggested in a comment above, use the #if UNITY_EDITOR pragma to avoid the error
I read your post and I have a similar problem with this.
Before I have built an apk file but it was not working on the emulator.
But it was working on Unity Editor well.
I couldn't find the reason for this problem but I think there is a problem when the scene is loading using SceneManager.LoadScene().
When I don't use this function, the error was fixed.
If you fix this problem, please post how did you do.
And I think it is better to avoid errors than fixing errors.
Good luck.
Related
I am learning Unity. Working through the rollaball tutorial, I have come as far as video 8, where I add the line "public float speed=0;" this reveals what I already suspected, namely that in some way my script does not "take" in the unity editor.
I use Visual Studio code as my normal editor. I told Unity that it is going to be my editor for scripts.
In this tutorial, I started by pressing a "new script" button as recommended by the tutorial, and created the file PlayerControl.cs in the editor. However, as the screenshot shows, the editor doesn't look like it has really taken possession of edited script, and it certainly hasn't added "speed" as a visible field. Besides which, nothing that I try will actually move the ball.
Okay, so my Unity install is brand-new, and I can easily believe that I might have missed a bit. But where to look, how to diagnose? Is there a log file I should be looking at?
The meaning of the OnMove method is not entirely clear from documentation that I can find. Is it called when the mouse moves? If so, it too is being unresponsive.
Tutorial:
https://learn.unity.com/tutorial/moving-the-player?uv=2020.2&projectId=5f158f1bedbc2a0020e51f0d#
System: Mac OS 11.6
VS Code 1.74.2
Script code is below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour {
public float speed = 0;
private RigidBody rb; // so Inspector doesn't see it
private float movementX, movementY;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<RigidBody>();
}
void OnMove(InputValue mvt)
{
Vector2 movementVector = mvt.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
}
I don't know whether you have installed the visual studio code package or not. This is required to correctly integrate VS Code and Unity.
Just try saving the script again and return to Unity. Unity should now refresh and recompile the script into assembly then there will be the change reflected in editor.
And for the part where you can't understand OnMove() that explanation is as follows:
Since you are using Unity's New Input System, you would have created an action map. Unity will automatically call functions for each action in Action Map which is named [On + ActionName] OnMove() in all scripts. Since, the Behavior in PlayerInput Component is Set to Send Messages.
I'm following a Unity Augmented Reality Tutorial using ARFoundation (I've made sure the package has installed correctly, along with ARkit).
My code follows his to the letter, and yet Raycast does not appear to be recognized. I get this error when I hover over it:
'ARSessionOrigin' does not contain a definition for 'Raycast' and no accessible extension method 'Raycast' accepting a first argument of type 'ARSessionOrigin' could be found (are you missing a using directive or an assembly reference?)
I can't figure out what the issue is, and I've redone the tutorial twice now (the second time using Unity's 3D template instead of ARCore because it seemed that ARFoundation was locked when I used ARCore template.) I'd greatly appreciate if someone could take a look and let me know if they have an idea of how to resolve it.
Thinking it had to do with ARFoundation not installing correctly, I double checked and ensured that it was, and was updated to the latest version. I re-checked the code multiple times for errors, and I still cannot figure out why Raycast isn't being recognized. Below is the Unity script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.Experimental.XR;
using UnityEngine.XR.ARSubsystems;
public class TapToPlaceObject : MonoBehaviour
{
private ARSessionOrigin arOrigin;
private Pose placementPose;
private bool placementPoseIsValid = false;
// Start is called before the first frame update
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
}
// Update is called once per frame
void Update()
{
UpdatePlacementPose();
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arOrigin.Raycast(screenCenter, hits, TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
}
}
}
Gotta google your problems, my dude.
From this post:
It seems that they have moved Raycast from ARSessionOrigin to ARRaycastManager in latest version. As mentioned in https://docs.unity3d.com/Packages/com.unity.xr.arfoundation#2.0/manual/index.html, you need to "add an ARRaycastManager to the same GameObject as the ARSessionOrigin".
Edit - you should also pay very close attention to the publication date for any tutorials. Some aspects of Unity have been stable for a very long time but some things break on a new year's release. UI Toolkit, AR, DOTS, etc. are all examples off the top of my head.
I am using Unity 2019.3.13f1 and Visual Studio Community 2019 version 16.5.4. I have the script InterfaceContainer.cs as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InterfaceContainer : MonoBehaviour {
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
}
}
public interface IItem {
public string Name { get; }
public string Path { get; }
public GameObject Icon { get; }
public void Open();
}
Visual Studio gives no compilation errors.
In Unity the inspector of the script says "No MonoBehaviour scripts in the file, or their names do not match the file name." And when I drag the script into a GameObject, it says "Can't add script component "InterfaceContainer" because this script class cannot be found. Make sure that there are no compile errors and that the file name and the class name match."
The names definitely match, because when I deleted the interface part the error didn't exist anymore.
I also tried deleting the class part. It didn't help.
Any subsequent scripts added had the exact same error, whether or not they contain any interfaces, or reference this script.
The weird thing is when I deleted the interface part of this script, refreshed Unity, added this part again, and refreshed Unity again, the error disappears. However all subsequently added scripts still have the same error.
I have no idea what causes this error, and have googled for a long time with no avail. Any help will be greatly appreciated.
EDIT: The error isn't gone when I removed the interface part and added it again; I can still drag the script as a component, when when I try entering playmode it asks me to fix all compiler errors.
Try this:
Right click in the Project Panel of Unity
Import New Asset... and select InterfaceContainer.cs
Try add this script as component again.
One thing I would try is to check if it happens in earlier versions of unity. With the unity hub its easy to have different versions of unity to check this kind of things. Its useful if you are working with one of the latests.
I can confirm that in 2018.4.12, I attach my monobehaviours with interfaces with no problem.
On the other hand you dont implement the Interface you define in your monobehaviour, although that should not be causing any problem, have you tried if implementing the interface in your monobehaviour if you got the error?
Hope that helps
I have a set of Asset Bundles that I load prefabs from. I don't simulate Asset Bundles in the editor, and when the Asset Bundles are downloaded from the website in the editor, the scripts and serialzed values work as expected.
However, when I actually make a WebGL build that uses those same Asset Bundles (also built for WebGL) and upload it, the prefabs all appear correct, but the info attached to them using Serializable fields of a MonoBehavior are all set to their default values. Am I missing some sort of flag for my Asset Bundle building or something?
The first time I ran into this issue (for my menu system) I went ahead and serialized the data to JSON to load later, but for this situation I don't view that as a viable solution.
The prefabs are models of metal parts, and said metal parts all have a specific ID (which is an int) which I use to represent the part.
I have cleared my cache in my test browser (firefox) and I am running in a private tab to prevent any data being saved between test sessions. I am sure that the asset bundles are being re-acquired properly as it takes about 4 eternities to download them on the internet I am on here.
public class PartInfo : MonoBehaviour
{
[SerializeField]
public float Length;
[SerializeField]
public string Sku;
[SerializeField]
public int Id;
void OnValidate()
{
if (Sku == "")
{
Sku = gameObject.name.ToLower();
}
}
}
and
public void AddItem(GameObject go)
{
PartInfo goInfo = go.GetComponent<PartInfo>();
Debug.Log($"Found info attatched to part! {goInfo} with values {goInfo.Sku}, {goInfo.Id}, and {goInfo.Length}!!");
}
EDIT:
I forgot to mention, this is the editor script I use to build the Asset Bundles:
[MenuItem("Assets/Create Asset Bundles")]
static void ExportBundle()
{
BuildPipeline.BuildAssetBundles(Application.dataPath + #"/../AssetBundles", BuildAssetBundleOptions.None, BuildTarget.WebGL);
}
I expect the same output I get in the editor:
Found info attatched to part! SHILT5(Clone) (PartInfo) with values shilt5, 406, and 7!!
To show in the Web GL build:
Found info attatched to part! with values , 0, and 0!!
(Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 48)
EDIT: I went ahead and updated Unity today, but it didn't help anything. I'm doing a non-stripped dev/debug build to see if I can figure anything out.
so I'm new to Unity and I've been trying to test the scene with the script attatched to a character. However, it keeps saying "The associated script cannot be loaded. Please fix any compile errors and assign a valid script." It also says that the name of the file could be different from the name in the code but it isnt, and also it says that the code could be missing MonoBehaviour Scripts. It wont even allow me to attach the script to characters because it cant find the script class.
I've copied and downloaded character movement codes from the internet but they didnt work either. I've also tried deleting and re-making the CS files but that didnt work either. Even adding empty scripts to characters didnt work unless i do it from "Add component"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
SpriteRenderer sprite;
Rigidbody2D rigid;
// Start is called before the first frame update
void Start()
{
sprite = GetComponent<SpriteRenderer>();
rigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (Input.GetKey("d"))
rigid.velocity = new Vector2(2, 0);
else if (Input.GetKey("a"))
rigid.velocity = new Vector2(-2, 0);
}
}
There are also these errors in Unity if that helps
I think your class name is different from file name.
Unity apparently can't handle apostrophes (single-quote ') in the directory name of the editor. You need to get rid of the apostrophe in your directory name. Once you make that change, Unity should be able to build the scripts as intended.
Edit: This has been fixed in more recent versions - see https://issuetracker.unity3d.com/issues/scripts-do-not-get-compiled-if-the-unity-editor-path-contains-apostrophes for reference
First, it is recommended to use "Add component" to create a script, if you want to attach it to a GameObject, as it automatically imports necessary libraries. Implementing MonoBehaviour is necessary for adding a script to a GameObject.
Second, FixedUpdate() should not be set to private, it does not need an access modifier, just like Start(), see https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html.
Third, the errors in your first screenshot seem to imply that there is a problem with your Unity installation. Try reinstalling it and make sure that the Editor you install matches your operating system (64 or 32 bit?).
Fourth, the second screenshot is shown when you use any obsolete libraries or classes, which does not seem to be the case in the script you shared.
Hope that helps.
It's basically because you deleted some script or renamed it or degraded unity version. you might have to reassign the script at the required position/component.
Note: Make sure that class name is the same as the script name in unity.