Gauss-Krüger system to Unity Coordinate Conversion

In my recent project, I am getting an object file via a request to REST API and found that the OBJs (object file) are in Gauss-Kruger System. I want to know that how exactly I place the model as I have several objects so coordinate conversion should work between UCS(unity coordinate system) and Gauss Kruger System. Previously I am able to convert UCS to Lat Long via Unity GPS Conversion project.

unity – Display musical symbol (unicode) in Text component not working?

I downloaded and specified to use a unicode font that supports musical symbols (Musica), but when I set the text value of the Text component to “𝄞” nothing is displayed? I tried using the unicode code point with U as well. What is going wrong?

(I could not get TextMesh Pro working either with that symbol.)

How can I play a youtube video in Unity if given the youtube URL link?

How can I play a youtube video in Unity if given the youtube URL link? I am using 2019.4.13
Is there a way to open webpages?

unity – Why the scene name is never change when loading another scene?

I have two scenes. Main Menu and Game.

When running the game it’s starting with the Main Menu scene loaded. Then when making a new game the Main Menu scene is unloaded and the Game scene is loaded but even if the Game scene is loaded it keep showing the Main Menu scene in the name :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class AudioManager : MonoBehaviour
{
    public GameObject gameAudio;

    private AudioSource audioSource;
    private string sceneName;
    private bool currentScene = false;

    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }

    // Start is called before the first frame update
    void Start()
    {
        // Create a temporary reference to the current scene.
        Scene currentScene = SceneManager.GetActiveScene();

        // Retrieve the name of this scene.
        sceneName = currentScene.name;

        audioSource = gameAudio.GetComponent<AudioSource>();

        var mainmenumusic = GameObject.Find("Main Menu Settings");
        audioSource.volume = mainmenumusic.GetComponent<AudioSource>().volume;
    }

    // Update is called once per frame
    void Update()
    {
        if (sceneName == "Game" && currentScene == false)
        {
            audioSource.Play();
            currentScene = true;
        }
        else
        {
            if (sceneName != "Game")
            {
                audioSource.Stop();
                currentScene = false;
            }
        }
    }

    //Called when Slider is moved
    public void changeVolume(float sliderValue)
    {
        audioSource = gameAudio.GetComponent<AudioSource>();
        audioSource.volume = sliderValue;
    }
}

In the Update even if the Game scene has loaded and only the Game scene is loaded it keep showing Main Menu in the sceneName :

if (sceneName == "Game" && currentScene == false)

sceneName is never “Game”

And a side question :

Why when I press the escape key back to the main menu it keep creating the Dont Destroy On Load object over and over again ? How can I avoid it from being creating the Dont Destroy On Load all the time ? This script is in my Game scene :

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class BackToMainMenu : MonoBehaviour
{
    public GameObject() objsToDisable;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                DisableEnableUiTexts(true);
                SceneManager.UnloadSceneAsync(0);
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                SceneManager.sceneLoaded += SceneManager_sceneLoaded;

                Cursor.visible = true;
            }
        }
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        DisableEnableUiTexts(false);
    }

    private void DisableEnableUiTexts(bool enabled)
    {
        foreach (GameObject go in objsToDisable)
        {
            if (go.name == "Cameras")
            {
                foreach(Transform child in go.transform)
                {
                    if(child.name == "Main Camera")
                    {
                        if (enabled == false)
                        {
                            child.GetComponent<Camera>().enabled = false;
                        }
                        else
                        {
                            child.GetComponent<Camera>().enabled = true;
                        }
                    }
                }
            }
            else
            {
                go.SetActive(enabled);
            }
        }
    }
}

unity – How can I integrate between the audio volumes settings in the main menu scene and the audio in the game scene?

I have two scenes only : Main Menu and Game
In the Game scene I keep all the game data and gameplay stuff.

In the Main Menu scene I have two sliders for volumes. One for the music and one for the sfx effects.
Both volumes and sliders are working fine and save the music/sfx volumes.

The problem is that the music in the main menu is not the same background music in the game scene.
Same for the sfx effect. In the main menu I just took some sfx effect and playing it when changing the volume.
In the game scene the background music is another one and I have also many audio sources with sfx effects. For example on the player I have a audio source with foot steps audio. On my droid I have audio source with shooting audio clip and so on.

What I want to do in my logic is when I change the volume/s in the main menu that it will effect the volume/s also in the game scene.

When the game start first time the main menu scene is loading and playing a music. Then when making a new game or loading a game the main menu is unloaded and the game scene is loaded with his own music and effects.

I also have in the game scene a script to return to the main menu with the escape key and back to the game. It’s a script for pausing/resuming the game and I want to pause/resume the game audio as well.
When making escape key and the game pause I want to pause also the audio in the game scene when pressing escape again back to the game to resume the audio from the last point.

This screenshot show the main menu with the two audio sources for music and sfx :

Main Menu audio settings

And this is the settings script in the main menu that control also the audio volumes :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using TMPro;
using System;
using UnityEngine.Events;
using System.Linq;

public class Settings : MonoBehaviour
{
    (SerializeField) private AudioSource() audioSources;
    public AudioMixer audioMixer;
    public TMP_Dropdown resolutionDropdown;
    public TMP_Dropdown qualityDropdown;
    public Text musicText;
    public Text sfxText;
    public Slider() audioSliders;
    public Toggle fullScreenToggle;

    private Resolution() resolutions;

    private void Awake()
    {
        audioSources = GetComponents<AudioSource>();

        resolutionDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("resolutionvalue", resolutionDropdown.value);
            PlayerPrefs.Save();

        }));

        qualityDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("qualityvalue", qualityDropdown.value);
            PlayerPrefs.Save();

        }));

        fullScreenToggle.onValueChanged.AddListener(new UnityAction<bool>(index =>
        {
            PlayerPrefs.SetInt("fullscreen", boolToInt(fullScreenToggle.isOn));
            PlayerPrefs.Save();

        }));
    }

    private void Start()
    {
        qualityDropdown.value = PlayerPrefs.GetInt("qualityvalue");

        var resolutions = Screen.resolutions.Where(resolution => resolution.refreshRate == 60).ToArray();
        resolutionDropdown.ClearOptions();

        List<string> options = new List<string>();

        int currentResolutionIndex = 0;
        for(int i = 0; i < resolutions.Length; i++)
        {
            string option = resolutions(i).width + " x " + resolutions(i).height;
            options.Add(option);

            if(resolutions(i).width == Screen.currentResolution.width &&
                resolutions(i).height == Screen.currentResolution.height)
            {
                currentResolutionIndex = i;
            }
        }

        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = PlayerPrefs.GetInt("resolutionvalue", currentResolutionIndex);
        resolutionDropdown.RefreshShownValue();

        float musicvolume = PlayerPrefs.GetFloat("musicvolume");
        float sfxvolume = PlayerPrefs.GetFloat("sfxvolume");

        musicText.text = musicvolume.ToString();
        sfxText.text = sfxvolume.ToString();
        audioSliders(0).value = musicvolume / 100f;
        audioSliders(1).value = sfxvolume / 100f;

        fullScreenToggle.isOn = intToBool(PlayerPrefs.GetInt("fullscreen", 0));
        
    }

    public void SetResolution(int resolutionIndex)
    {
        if (resolutions != null)
        {
            Resolution resolution = resolutions(resolutionIndex);
            Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
        }
    }

    public void SetMusicVolume(float volume)
    {
        audioMixer.SetFloat("musicvol", Mathf.Log10(volume) * 20);
        musicText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("musicvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));
    }

    public void SetSfxVolume(float volume)
    {
        audioMixer.SetFloat("sfxvol", Mathf.Log10(volume) * 20);
        sfxText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("sfxvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));

        if (!audioSources(1).isPlaying)
            audioSources(1).Play();
    }

    public void SetQuality(int qualityIndex)
    {
        QualitySettings.SetQualityLevel(qualityIndex);
    }

    public void SetFullscreen(bool isFullscreen)
    {
        Screen.fullScreen = isFullscreen;        
    }

    int boolToInt(bool val)
    {
        if (val)
            return 1;
        else
            return 0;
    }

    bool intToBool(int val)
    {
        if (val != 0)
            return true;
        else
            return false;
    }
}

At lines 97 and 105 I’m setting and saving the volumes : function SetMusicVolume and SetSfxVolume.
The music and sfx are working fine in the main menu.

Now the Game scene :

In the Game scene I have this script to pause the game and to resume, still without the audio pause/resume part that I’m not sure how to do : And also here it should keep the changes of the volumes in both scenes in case I press the escape key and make changes in the main menu and then back to the game scene it should resume the audio but also to apply the volume/s changes if made :

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class BackToMainMenu : MonoBehaviour
{
    public GameObject() objsToDisable;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                DisableEnableUiTexts(true);
                SceneManager.UnloadSceneAsync(0);
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                SceneManager.sceneLoaded += SceneManager_sceneLoaded;

                Cursor.visible = true;
            }
        }
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        DisableEnableUiTexts(false);
    }

    private void DisableEnableUiTexts(bool enabled)
    {
        foreach (GameObject go in objsToDisable)
        {
            if (go.name == "Cameras")
            {
                foreach(Transform child in go.transform)
                {
                    if(child.name == "Main Camera")
                    {
                        if (enabled == false)
                        {
                            child.GetComponent<Camera>().enabled = false;
                        }
                        else
                        {
                            child.GetComponent<Camera>().enabled = true;
                        }
                    }
                }
            }
            else
            {
                go.SetActive(enabled);
            }
        }
    }
}

I also created one audio mixer with two groups name : Main Menu Audio and Game Audio all the Music’s and sfx’s are exposed already :

Audio mixer

My problem is that I can’t figure out how to make the volumes in the main menu to affect the volumes in the game scene too. and how to resume/pause the audio in the game scene in the back to the main menu script ?

unity – How to Make Saving System More Secure

Since you wrote in a comment it is for an offline game, the short answer is: you can’t.

If the player is the owner of the whole game (since it offline), any kind of mechnism can be prevented if he is dedicated enough to figure out how you obscured your data. You can only make it harder for him.

You need to prevent memory manipulation, else the player could either freeze his hitpoints, ammo, money, etc or increase it to his liking.

The second part is you need to protect the save file itself against manipulation. Since he can read it as well, you need to make it harder for him to read and change values. Binary files, custom formats and a hash of everything are doing the job. The draw back (if that is one for you) is, if he really tries to manipulate the file, he might create new run time errors when you try to read your own file since the format got broken (and the player will certainly blame it on you why all his items are gone)

There is the opinion that if the game is offline, you should let the player do what he wants. Maybe the game is too hard and he would otherwise stop playing. Maybe he is lacking time for farming. As long as he is the only player, all he can do is boost himself and has no effect on the play experience of other players.

unity – How to Implement One-Way Slopes?

I am working on a 2D platformer in Unity and am doing my own collision detection.

I was previously using the method described in Sebastian Lague’s popular YouTube tutorial, where you break your velocity into its horizontal and vertical components, then cast a series of rays horizontally and vertically from some skin_distance within the characters bounding box, checking for collisions. The length of the raycasts is the length of the velocity component plus the skin_distance. If any of the rays collide, you curtail the ray length and continue to iterate through the remaining arrays, until you’re out of arrays, at which point you set the velocity to your final ray length (minus skin_distance).

This method works well enough, and Sebastian’s tutorials even extend the method to solid slopes.

I want one-way slopes, however. One-way slopes are slopes that you can jump up through from underneath to land on them from above.

I’ve been at it for a week now, and I can’t seem to extend Sebastian’s method to work for them.

I’ve tried several things. First, I’ve represented the slopes & my flat one-way platforms as line segments using EdgeCollider2Ds. Then, I created methods for OneWayHorizontalCollisionDetection() and OneWayVerticalCollisionDetection(). The former checks if a velocity-lengthed horizontal ray from the bottomleft or bottomright point of the character’s bounding_box intersects a slope. If it does, x-vel and y-vel are adjusted to snap the character onto the slope and move the character up the slope.

In the latter, for jumping up through the slope, if my character is ever moving down and one of its vertical rays hits the slope, I check to make sure the correct bottom corner point is also above the slope. If it is, then I’d curtail the velocity so the character landed on the slope properly (see diagram below).

No matter how much I try to massage things, however, I always encounter an issue.
Part of the problem with this method, I think, concerns an asymmetry with vertical detection versus horizontal detection.

Consider the below diagram. When doing vertical collision detection, if my character is falling and the green point in the bottom right corner is above the slope, and the ray intersects, I’ll move the char down so that green point is flush with the slope. The character sits nicely on the slope and everything seems fine.

enter image description here

If I then press right to start moving up the slope, my horizontal collision detection will see the slope on the right, and snap the green point on the right side of the character to the slope. The character will then move up the slope just fine. If I then stop moving, however, because the bottom green point is now below the slope, the character will fall through the slope.

Even trying to massage by way around this problem, I’ve encountered a whole host of other issues, particularly at the point of transition from the slope to the flat platform at the top. Issues with floating point imprecision interfering with is point.y >= point2.y complicated matters even more.

I’ve come to think this “skin distance raycast” method is not the correct way to proceed if I want one-way slopes. I am simply running into too many issues.

I tried converting my system to use boxcasts of my character’s BoxCollider2D, but it didn’t pan out.

Then, I tried to move back to raycasts, but I tried casting them at the true corners of my bounding_box, rather than some skin width inside. I didn’t make much progress there either, though my gut tells me using true corners is going to be the most elegant way to implement one-way slopes. At least using true corners, you know exactly which point you want to be snug on the slope.

So, my question is, what is a viable collision detection paradigm for one-way slopes? Could anyone sketch for me what an implementation of one-way slopes would looks like?

I know there’s dozens of questions about slope collision detection, but I have yet to find a single one which specifically mentions one-way slopes (which seems to be a harder problem).

NOTE: I am open to both solutions that put the bounding box bottom corner on the slope, as well as those that put the bounding box’s midbottom point on the slope, though I would prefer the former. I am only trying to accommodate 22.5-degree slopes.

unity – Rotate around moving object

You can store your current pivot object, direction from it, and distance away in member variables.

Overwrite these values when you start rotating around a new pivot, but then keep the distance variable fixed at that value for future updates.

In your Update (or LateUpdate, if you want to be sure this runs after any Update scripts or animations that move your pivot objects around), rotate your direction, scale it by your distance, and add it to the pivot position to find your new location relative to it.

Here’s one way that could look:

public class RotateAround : MonoBehaviour {

    public float rotationSpeed = 90f;

    Transform _pivot;
    Vector3 _offsetDirection;
    float _distance;

    public void SetPivot(Transform pivot) {
        if (pivot != null) {
            _pivot = pivot;
            _offsetDirection = transform.position - pivot.position;
            _distance = _offsetDirection.magnitude;
        } else {
            _pivot = null;
        }
    }

    void Update() {
        if (_pivot == null) return;

        Quaternion rotate = Quaternion.Euler(0, 0, rotationSpeed * Time.deltaTime);

        _offsetDirection = (rotate * _offsetDirection).normalized;

        transform.position = _pivot.position + _offset * _distance;
    }
}

unity – Save Script Doesn’t Save Item Variables

I’ve been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player’s itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don’t receive any errors or warnings in the Console. Here is my script to the Saving System:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class InventorySave : MonoBehaviour
{
    // Public variables for inventory and health
    private GameObject itemHolder;
    private ItemInformation myItemAmount;

    // Initiates before the first frame
    void Start()
    {
        // Gets components for the player variables
        itemHolder = transform.gameObject;
        myItemAmount = itemHolder.GetComponent<ItemInformation>();
    }

    // Function that will be called when player saves game from pause menu
    public void SaveGame()
    {
        // Creates file to store variables
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/SaveData.dat");
        SaveData data = new SaveData();

        // Gets the player data
        data.itemSave = myItemAmount.itemAmount;

        // Writes player data to file and encrypts it
        bf.Serialize(file, data);
        file.Close();
    }
}

// Holds data that is to be saved
(Serializable)
class SaveData
{
    // Variables for save file
    public int itemSave;
}

Is it possible to render / project / flatten a 3d model onto a 2d plane in Unity?

If I have a 3d Object (character) could I use a renderer / shader / camera mode to essentially render the 3d object as a 2d sprite?

Not looking for a full tutorial on this one, I realize its a large question; just looking for a direction to head in.