I'm making an android 2D game on Unity 2020.3.30f1. I inserted a scroll view into the project, when the game starts, the content and buttons change size and the buttons flip. What should I do?
Maybe it has nothing to do with the code?
Thank you in advance!
Sorry if bad code.
Here's what it looks like:
It should be:
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class AchMenu : MonoBehaviour
{
public int money;
public int total_money;
[SerializeField] bool isFirst;
public string[] arrayTitles;
public Sprite[] arraySprites;
public GameObject button;
public GameObject content;
private List<GameObject> list = new List<GameObject>();
private VerticalLayoutGroup _group;
void Start()
{
money = PlayerPrefs.GetInt("money");
total_money = PlayerPrefs.GetInt("total_money");
isFirst = PlayerPrefs.GetInt("isFirst") == 1 ? true : false;
RectTransform rectT = content.GetComponent<RectTransform>();
rectT.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
_group = GetComponent<VerticalLayoutGroup>();
setAchievs();
if (isFirst)
{
StartCoroutine(IdleFarm());
}
}
private void RemovedList()
{
foreach (var elem in list)
{
Destroy(elem);
}
list.Clear();
}
void setAchievs()
{
RectTransform rectT = content.GetComponent<RectTransform>();
rectT.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
RemovedList();
if (arrayTitles.Length > 0)
{
var pr1 = Instantiate(button, transform);
var h = pr1.GetComponent<RectTransform>().rect.height;
var tr = GetComponent<RectTransform>();
tr.sizeDelta = new Vector2(tr.rect.width, h * arrayTitles.Length);
Destroy(pr1);
for (var i = 0; i < arrayTitles.Length; i++)
{
var pr = Instantiate(button, transform);
pr.GetComponentInChildren<Text>().text = arrayTitles[i];
pr.GetComponentsInChildren<Image>()[1].sprite = arraySprites[i];
var i1 = i;
pr.GetComponent<Button>().onClick.AddListener(() => GetAchievement(i1));
list.Add(pr);
}
}
}
void GetAchievement(int id)
{
switch (id)
{
case 0:
Debug.Log(id);
break;
case 1:
Debug.Log(id);
money += 10;
PlayerPrefs.SetInt("money", money);
break;
case 2:
Debug.Log(id);
break;
}
}
IEnumerator IdleFarm()
{
yield return new WaitForSeconds(1);
money++;
Debug.Log(money);
PlayerPrefs.SetInt("money", money);
StartCoroutine(IdleFarm());
}
public void ToMenu()
{
SceneManager.LoadScene(0);
}
// Update is called once per frame
void Update()
{
}
}
Related
I'm working on a portal system and am up to making the traveller go through the portal. For this, I just set the traveller's position to the position of the other portal. When I do this, however, the Z rotation of the camera gets skewed, and they are teleported slightly higher than they should. Any help is welcome <3
Portal Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Portal : MonoBehaviour
{
//Portal Camera Positioning
public Portal linkedPortal;
private Camera portalCam;
private Camera playerCam;
//Portal Sceen Texture
private PortalScreen portalScreen;
private MeshRenderer screenRen;
private RenderTexture viewTexture;
//Travellers
//[SerializableField]
List<PortalTraveller> trackedTravellers;
public Vector3 desiredCameraRotation;
public Vector3 desiredCameraPosition;
private Transform globalRuler;
PortalTraveller[] travellersToAdd;
[HideInInspector]
public float travellerDistance;
//Debug
[HideInInspector]
public float dstToPlayer;
void Awake()
{
playerCam = Camera.main;
portalCam = linkedPortal.GetComponentInChildren<Camera>();
portalScreen = GetComponentInChildren<PortalScreen>();
screenRen = portalScreen.GetComponent<MeshRenderer>();
globalRuler = GameObject.FindWithTag("GlobalRuler").transform;
trackedTravellers = new List<PortalTraveller>();
travellersToAdd = GameObject.FindObjectsOfType<PortalTraveller>();
foreach (PortalTraveller traveller in travellersToAdd)
{
if (!trackedTravellers.Contains(traveller))
{
trackedTravellers.Add(traveller);
}
}
}
void Update()
{
Render();
}
static bool VisibleFromCamera(Renderer renderer, Camera camera)
{
Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
return GeometryUtility.TestPlanesAABB(frustumPlanes, renderer.bounds);
}
void Render()
{
if (!VisibleFromCamera(screenRen, playerCam))
{
return;
}
desiredCameraPosition = transform.position - (playerCam.transform.position - linkedPortal.portalScreen.screenPos);
desiredCameraPosition.y = playerCam.transform.position.y;
desiredCameraRotation = playerCam.transform.eulerAngles + new Vector3 (0f, 180f, 0f);
portalCam.transform.position = desiredCameraPosition;
portalCam.transform.eulerAngles = desiredCameraRotation;
if (viewTexture == null || viewTexture.width != Screen.width || viewTexture.height != Screen.height)
{
if (viewTexture != null)
{
viewTexture.Release();
}
viewTexture = new RenderTexture (Screen.width, Screen.height, 0);
portalCam.targetTexture = viewTexture;
screenRen.material.SetTexture("_MainTex", viewTexture);
}
}
void LateUpdate()
{
HandleTravellers();
}
void HandleTravellers()
{
for (int i = 0; i < trackedTravellers.Count; i++)
{
PortalTraveller traveller = trackedTravellers[i];
Transform travellerT = trackedTravellers[i].transform;
Vector3 toTraveller = traveller.transform.position - transform.position;
int portalSide = System.Math.Sign(Vector3.Dot(toTraveller, transform.right));
int portalSideOld = System.Math.Sign(Vector3.Dot(traveller.previousTravellerVector, transform.right));
travellerDistance = Mathf.Abs(Vector3.Distance(transform.position, travellerT.position));
//Debug.Log("Handled");
if (travellerDistance > linkedPortal.travellerDistance)
{
break;
}
if (portalSide < portalSideOld && travellerDistance < globalRuler.transform.lossyScale.z / 2 )
{
//Debug.Log(travellerDistance);
var positionOld = travellerT.position;
var rotationOld = travellerT.rotation;
Quaternion rot = Quaternion.Euler(desiredCameraRotation.x, desiredCameraRotation.y, 0f);
traveller.Teleport(transform, linkedPortal.transform, desiredCamerxaPosition, rot);
traveller.previousTravellerVector = toTraveller;
//trackedTravellers.RemoveAt(i);
i--;
}
else
{
traveller.previousTravellerVector = toTraveller;
dstToPlayer = Mathf.Abs(Vector3.Distance(transform.position, travellerT.position));
}
}
}
void OnValidate()
{
if (linkedPortal != null)
{
linkedPortal.linkedPortal = this;
}
travellersToAdd = GameObject.FindObjectsOfType<PortalTraveller>();
}
}
Traveller Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PortalTraveller : MonoBehaviour
{
public Vector3 previousTravellerVector;
public void Teleport(Transform originalPortal, Transform linkedPortal, Vector3 pos, Quaternion rot)
{
transform.position = pos;
transform.rotation = rot;
}
}
So I recently finished Sebastian Lague's Create a Game series and everything works fine except for the music. I don't know the cause of issue but while in gameplay scene another theme just starts playing, same thing happens when I restart the game and this also happens in Sebastian's finale version of the game so I can't find the answer there. I didn't really try anything since I don't have an idea what cause of the issue may be, so I decided to write here and maybe someone will know the answer. Thanks in advance!
Audio Manager:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class AudioManager : MonoBehaviour
{
public enum AudioChannel { Master, Sfx, Music };
public float masterVolumePercent { get; private set; }
public float sfxVolumePercent { get; private set; }
public float musicVolumePercent { get; private set; }
private AudioSource sfx2DSource;
private AudioSource[] musicSources;
private int activeMusicSourceIndex;
public static AudioManager instance;
private Transform audioListener;
private Transform playerT;
private SoundLibrary library;
private void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
library = GetComponent<SoundLibrary>();
musicSources = new AudioSource[2];
for (int i = 0; i < 2; i++)
{
GameObject newMusicSource = new GameObject("Music source " + (i + 1));
musicSources[i] = newMusicSource.AddComponent<AudioSource>();
newMusicSource.transform.parent = transform;
}
GameObject newSfx2Dsource = new GameObject("2D sfx source");
sfx2DSource = newSfx2Dsource.AddComponent<AudioSource>();
newSfx2Dsource.transform.parent = transform;
audioListener = FindObjectOfType<AudioListener>().transform;
if (FindObjectOfType<PlayerInput>() != null)
{
playerT = FindObjectOfType<PlayerInput>().transform;
}
masterVolumePercent = PlayerPrefs.GetFloat("master vol", 1);
sfxVolumePercent = PlayerPrefs.GetFloat("sfx vol", 1);
musicVolumePercent = PlayerPrefs.GetFloat("music vol", 1);
}
}
void Update()
{
if (playerT != null)
{
audioListener.position = playerT.position;
}
}
public void SetVolume(float volumePercent, AudioChannel channel)
{
switch (channel)
{
case AudioChannel.Master:
masterVolumePercent = volumePercent;
break;
case AudioChannel.Sfx:
sfxVolumePercent = volumePercent;
break;
case AudioChannel.Music:
musicVolumePercent = volumePercent;
break;
}
musicSources[0].volume = musicVolumePercent * masterVolumePercent;
musicSources[1].volume = musicVolumePercent * masterVolumePercent;
PlayerPrefs.SetFloat("master vol", masterVolumePercent);
PlayerPrefs.SetFloat("sfx vol", sfxVolumePercent);
PlayerPrefs.SetFloat("music vol", musicVolumePercent);
PlayerPrefs.Save();
}
public void PlayMusic(AudioClip clip, float fadeDuration = 1)
{
activeMusicSourceIndex = 1 - activeMusicSourceIndex;
musicSources[activeMusicSourceIndex].clip = clip;
musicSources[activeMusicSourceIndex].Play();
StartCoroutine(AnimateMusicCrossfade(fadeDuration));
}
public void PlaySound(AudioClip clip, Vector3 pos)
{
if (clip != null)
{
AudioSource.PlayClipAtPoint(clip, pos, sfxVolumePercent * masterVolumePercent);
}
}
public void PlaySound(string soundName, Vector3 pos)
{
PlaySound(library.GetClipFromName(soundName), pos);
}
public void PlaySound2D(string soundName)
{
sfx2DSource.PlayOneShot(library.GetClipFromName(soundName), sfxVolumePercent * masterVolumePercent);
}
IEnumerator AnimateMusicCrossfade(float duration)
{
float percent = 0;
while (percent < 1)
{
percent += Time.deltaTime * 1 / duration;
musicSources[activeMusicSourceIndex].volume = Mathf.Lerp(0, musicVolumePercent * masterVolumePercent, percent);
musicSources[1 - activeMusicSourceIndex].volume = Mathf.Lerp(musicVolumePercent * masterVolumePercent, 0, percent);
yield return null;
}
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode sceneMode)
{
if (playerT == null)
{
if (FindObjectOfType<PlayerInput>() != null)
playerT = FindObjectOfType<PlayerInput>().transform;
}
}
}
Music Manager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MusicManager : MonoBehaviour
{
[SerializeField] private AudioClip mainTheme;
[SerializeField] private AudioClip menuTheme;
private string sceneName;
private void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void PlayMusic()
{
AudioClip clipToPlay = null;
if(sceneName == "Main Menu")
{
if(clipToPlay == null)
clipToPlay = menuTheme;
}
else if(sceneName == "Gameplay")
{
if(clipToPlay == null)
clipToPlay = mainTheme;
}
if(clipToPlay != null)
{
AudioManager.instance.PlayMusic(clipToPlay, 2);
Invoke("PlayMusic", clipToPlay.length);
Debug.Log(clipToPlay.length);
}
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode sceneMode)
{
if(sceneName != scene.name)
{
sceneName = scene.name;
Invoke("PlayMusic", .2f);
}
}
}
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;
public AudioMixer audioMixer;
public static bool gameSceneLoaded;
private void Awake()
{
gameSceneLoaded = true;
}
// Start is called before the first frame update
void Start()
{
audioMixer.SetFloat("gamemusicvolume", Mathf.Log10(PlayerPrefs.GetFloat("mainmenumusicvolume")) * 20);
}
// 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)
{
audioMixer.SetFloat("gamemusicvolume", Mathf.Log(0.0001f) * 20);
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);
}
}
}
}
When running the game the Main Menu scene start then when making a new game the Game scene is loaded and then here in the Start I'm getting the Main Menu volume float parameter and set it to the Game Music volume.
void Start()
{
audioMixer.SetFloat("gamemusicvolume", Mathf.Log10(PlayerPrefs.GetFloat("mainmenumusicvolume")) * 20);
}
When in the Main Menu scene the volume is -4.01 dB of the main menu music.
Main Menu music volume is -4.01 dB
Then when it's getting the volume of the main menu and set it to the Game music volume the Game music volume is 35.99 dB and I can't figure out why it's setting the volume to so high value ?
The game music volume value is 35.99 dB
Could be the calculation to get the volume in the Start is wrong ?
It should not be Log10 ? Or not * 20 ?
audioMixer.SetFloat("gamemusicvolume", Mathf.Log10(PlayerPrefs.GetFloat("mainmenumusicvolume")) * 20);
How come it's getting from -4.01 dB to 35.99 dB ?
This script in the Mein Menu scene is setting the music and sfx volumes of the main menu using ui sliders :
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("mainmenumusicvolume");
float sfxvolume = PlayerPrefs.GetFloat("mainmenusfxvolume");
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("mainmenumusicvolume", Mathf.Log10(volume) * 20);
musicText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();
PlayerPrefs.SetFloat("mainmenumusicvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));
}
public void SetSfxVolume(float volume)
{
audioMixer.SetFloat("mainmenusfxvolume", Mathf.Log10(volume) * 20);
sfxText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();
PlayerPrefs.SetFloat("mainmenusfxvolume", (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;
}
}
The SetMusicVolume is called by the slider event of the main menu music.
It seems that you are mixing some of the string parameters.
In your first script you're setting the audio mixer gamemusicvolume parameter like this:
audioMixer.SetFloat("gamemusicvolume", Mathf.Log10(PlayerPrefs.GetFloat("mainmenumusicvolume")) * 20);
And then in the second script you're setting the audio mixer mainmenumusicvolume parameter instead of the gamemusicvolume parameter.
audioMixer.SetFloat("mainmenumusicvolume", Mathf.Log10(volume) * 20);
Moreover, later in the first script you set the gamemusicvolume to an even lower value:
audioMixer.SetFloat("gamemusicvolume", Mathf.Log(0.0001f) * 20);
All in all, this code feels wrong and overcomplicated. Why do you save a value and then do Log * 20 manipulations? Why not just save the actual value that you want, keep your code simple.
Hy what i'm trying to do is to get all position from linerender and save it a a list of vector3 than save it in a firebase i did that so far now what i'm trying to is is to get the data that i save from firebase than save it again in a vector3 list so i can put it in the setposition linerender i try to do that but i always get a null result i didn't know why !!
the problem is i didn't figure out how to get the data i always get a null result
this is my code
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Path : MonoBehaviour
{
[SerializeField] private List<Transform> checkpoints = new List<Transform>();
private LineRenderer linerenderer;
public Material TheLineMateriel;
public static bool _ispressed = false;
private string DATA_URL = "https://kataraproject-a233a.firebaseio.com/";
private DatabaseReference reference;
Player playerInstance = new Player();
List<GetPosition> tmpList = new List<GetPosition>();
// Start is called before the first frame update
void Start()
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
reference = FirebaseDatabase.DefaultInstance.RootReference;
GameObject lineObject = new GameObject();
this.linerenderer = lineObject.AddComponent<LineRenderer>();
this.linerenderer.startWidth = 0.05f;
this.linerenderer.endWidth = 0.05f;
this.linerenderer.positionCount = checkpoints.Count;
this.linerenderer.material = TheLineMateriel;
}
// Update is called once per frame
void Update()
{
this.DrawLine();
}
private void DrawLine()
{
Vector3[] checkpointsArray = new Vector3[this.checkpoints.Count];
for (int i = 0; i < this.checkpoints.Count; i++) {
Vector3 checkpointPos = this.checkpoints[i].position;
checkpointsArray[i] = new Vector3(checkpointPos.x, checkpointPos.y, 0f);
}
Vector3[] newPos = new Vector3[linerenderer.positionCount];
this.linerenderer.SetPositions(checkpointsArray);
linerenderer.GetPositions(newPos);
if ( _ispressed == true)
{
playerInstance.Position = newPos;
writeNewPosition("1");
_ispressed = false;
}
}
public void PostPosition ()
{
_ispressed = true;
}
public void GetPosition()
{
Firebase.Database.FirebaseDatabase dbInstance = Firebase.Database.FirebaseDatabase.DefaultInstance;
dbInstance.GetReference("Positions").GetValueAsync().ContinueWith(task => {
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
foreach (DataSnapshot user in snapshot.Children)
{
IDictionary dictUser = (IDictionary)user.Value;
GetPosition newplayer = new GetPosition(dictUser);
tmpList.Add(newplayer);
foreach (var item in dictUser.Values)
{
Debug.Log(item);
Debug.Log("" + dictUser["Position"] );
}
}
}
});
}
private void writeNewPosition(string positionId)
{
string json = JsonUtility.ToJson(playerInstance);
reference.Child("Positions").Child(positionId).SetRawJsonValueAsync(json);
}
}
Can someone help me please and sorry for my enghlish
I find a way how to get the data from firebase this is the new script that I Update I used JSON .NET For Unity
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SetPath : MonoBehaviour
{
[SerializeField] private List<Transform> checkpoints = new List<Transform>();
private LineRenderer linerenderer;
public Material TheLineMateriel;
//Firebase
public static bool _ispressed = false;
private string DATA_URL = "https://kataraproject-a233a.firebaseio.com/";
private DatabaseReference reference;
Positions playerInstance = new Positions();
List<Vector3> tmpList = new List<Vector3>();
public static string Json;
bool liste_done = false;
Vector3 newPosition;
public List<Vector3> listOfPosition = new List<Vector3>();
// Start is called before the first frame update
private void Awake()
{
//FireBase
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
reference = FirebaseDatabase.DefaultInstance.RootReference;
}
void Start()
{
FirebaseDatabase.DefaultInstance.GetReference("Positions").GetValueAsync().ContinueWith(task => {
if (task.IsFaulted)
{
Debug.Log("No snapshot");
// Handle the error...
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
//Debug.Log("Snapshot:= " + task.Result.Value);
int i = 0;
foreach (DataSnapshot user in snapshot.Children)
{
// IDictionary dictUser = (IDictionary)user.Value;
//Debug.Log(dictUser.Keys);
Positions client = JsonConvert.DeserializeObject<Positions>(user.GetRawJsonValue());
foreach (var item in client.Position)
{
newPosition.x = item.x;
newPosition.y = item.y;
newPosition.z = 0;
checkpoints[i].gameObject.SetActive(true);
checkpoints[i].position = newPosition;
i++;
}
//Debug.Log(user.GetRawJsonValue());
}
//DrawLine
GameObject lineObject = new GameObject();
this.linerenderer = lineObject.AddComponent<LineRenderer>();
this.linerenderer.startWidth = 0.05f;
this.linerenderer.endWidth = 0.05f;
this.linerenderer.positionCount = checkpoints.Count;
this.linerenderer.material = TheLineMateriel;
}
});
}
// Update is called once per frame
void Update()
{
this.DrawLine();
}
private void DrawLine()
{
Vector3[] checkpointsArray = new Vector3[this.checkpoints.Count];
for (int i = 0; i < this.checkpoints.Count; i++)
{
Vector3 checkpointPos = this.checkpoints[i].position;
checkpointsArray[i] = new Vector3(checkpointPos.x, checkpointPos.y, 0f);
}
Vector3[] newPos = new Vector3[linerenderer.positionCount];
this.linerenderer.SetPositions(checkpointsArray);
linerenderer.GetPositions(newPos);
if (_ispressed == true)
{
playerInstance.Position = newPos;
writeNewPosition("1");
_ispressed = false;
Debug.Log("Saving is done");
}
}
//Save Data in fireBase
private void writeNewPosition(string positionId)
{
string json = JsonUtility.ToJson(playerInstance);
reference.Child("Positions").Child(positionId).SetRawJsonValueAsync(json);
}
//Button to save Data
public void PostPosition()
{
_ispressed = true;
}
public void NextScene()
{
SceneManager.LoadScene("PlayerSelmaNew");
}
}
so I have like 5 game object in my scene but I only scale each of them separately. However when I try to do that all of them start scaling simultaneously. Also, I have a placement indicator that would be used to instantiate the object on the plane. It seems that instead of the object itself, the placement indicator is the one that gets scaled. How should I fix that?
I have tried deactivating the placement indicator but did not work.
Here is the code for instantiating objects:
I limited the obj number to 5.
I use this script instead of the usual "PlaceonPlane" script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.Experimental.XR;
using UnityEngine.UI;
using UnityEngine.XR.ARSubsystems;
public class ARTaptoPlaceObject : MonoBehaviour
{
private ARSessionOrigin arOrigin;
GameObject spawnedobj;
public GameObject placementIndicator;
private ARRaycastManager arRaycast;
public Pose placementPose;
public UIContoller sc;
public bool placementPoseIsValid = false;
private int count;
private string valu;
string prefabs;
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
arRaycast = FindObjectOfType<ARRaycastManager>();
count = 0;
}
// Update is called once per frame
void Update()
{
UpdatePlacementPose();
UpdatePlacementIndicator();
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
if (placementPoseIsValid && Input.GetTouch(i).tapCount == 2)
{
PlaceObject();
}
}
}
}
public void PlaceObject()
{
if (count <= 4)
{
if (sc.objectToPlace != null)
{
spawnedobj = Instantiate(sc.objectToPlace, placementPose.position, placementPose.rotation);
arOrigin.MakeContentAppearAt(spawnedobj.transform, spawnedobj.transform.position, spawnedobj.transform.rotation);
count++;
}
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementIndicator()
{
if (placementPoseIsValid && count <= 4 && sc.active == false)
{
placementIndicator.SetActive(true);
placementIndicator.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arRaycast.Raycast(screenCenter, hits, UnityEngine.XR.ARSubsystems.TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
var cameraForward = Camera.current.transform.forward;
var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
placementPose.rotation = Quaternion.LookRotation(cameraBearing);
}
}
}
and here is the Scaler script that's attached to the button that would scale the object.
public class Scaler : MonoBehaviour
{
public UIContoller uc;
public ARTaptoPlaceObject ap;
private GameObject ReferenceToScale;
public void OnValueChange()
{
ReferenceToScale = (UnityEngine.GameObject)Resources.Load(uc.s_count, typeof(GameObject));
Vector3 t = ReferenceToScale.transform.localScale;
Vector3 scaleValue = t * 1.1f;
ReferenceToScale.transform.localScale = scaleValue;
}
Also the "objectToPlace" itself is in the "UI.Controller" script as I could not view it in the scene when it was in the "ARTaptoPlace" script