C# Unity Text array to string to show in GameScene - c#

I have a text array that calculates a sum: y = ax + b and now I want it to put the results of Y in a table, but I would have no idea how it should be. If I put a Debug.Log in, it sums correctly. I have no idea how to put the values of an array in a string so that it shows the values in a table in the game scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Line : MonoBehaviour
{
public LineRenderer lijn;
public InputField A;
public InputField B;
public float valueA;
public float valueB;
public int somX;
public double somY;
private int num = 0;
public Text[] xTabel;
public Text[] ytabel;
public Vector3 lijnposition;
void Update()
{
lijn.startWidth = 0.2F;
lijn.endWidth = 0.2F;
for(int i = -2; i < 4; i++)
{
somY = valueA *(somX * i) + valueB;
//xTabel[num] = somX.ToString();
//ytabel[num] = somY.ToString();
lijn.SetPosition(i, lijnposition);
Debug.Log(somY);
}
}
}

Related

Unity exploded view script does not seem to work but is also not turning up any errors

I have been working with some script which is supposed to cause the childmeshes of an object move away from their center by a certain distance on wake, Unfortunately while I am not getting any errors, the script also doesnt seem to work no matter what values I adjust. I tried to debug but am still struggling a bit, Any advice would be appreciated.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Interactions
{
public class ExplodedViewPart
{
public Vector3 StartPosition { get; }
public Vector3 Destination;
public float MoveDistance
{
set => Destination = m_meshCenter * value;
}
private readonly Vector3 m_meshCenter;
public ExplodedViewPart(Vector3 startPosition, Vector3 meshCenter, float moveDistance)
{
m_meshCenter = meshCenter;
StartPosition = startPosition;
Destination = meshCenter * moveDistance;
}
}
public class ExplodedView : MonoBehaviour
{
[Range(0.0f, 1.0f)]
[SerializeField] private float m_percentage;
[SerializeField] private float m_moveDistance = 3f;
private float m_oldMoveDistance = 3f;
private readonly List<ExplodedViewPart> m_parts = new List<ExplodedViewPart>();
private readonly List<Transform> m_partTransforms = new List<Transform>();
private void Awake()
{
foreach (var component in GetComponentsInChildren<MeshRenderer>())
{
Transform partTransform = component.transform;
m_partTransforms.Add(partTransform);
m_parts.Add(new ExplodedViewPart(partTransform.position, component.bounds.center, m_moveDistance));
}
}
private void ChangeMaxDistance(float value)
{
for (int i = 0; i < m_partTransforms.Count; i++)
{
m_parts[i].MoveDistance = value;
}
}
private void OnValidate()
{
if (Math.Abs(m_oldMoveDistance - m_moveDistance) > float.Epsilon)
{
ChangeMaxDistance(m_moveDistance);
m_oldMoveDistance = m_moveDistance;
}
Explode(m_percentage);
}
public void Explode(float percentage)
{
for (int i = 0; i < m_partTransforms.Count; i++)
{
m_partTransforms[i].position = (1 - percentage) * m_parts[i].StartPosition +
percentage * m_parts[i].Destination;
}
}
}
}

Having problem with the Dictionary in unity

I am currently programming a game in which an infinite procedural city is generated. so far everything works but because it leads to laggs if there are too many objects in the scene I wanted to make a script in which objects only appear near the player. I watched this video for help:https://www.youtube.com/watch?v=xlSkYjiE-Ck. When I tried to link this to my script (GenerateBuilding script) this error came:ArgumentException:
An item with the same key has already been added. Key: (0.0, 1.0)
System.Collections.Generic.Dictionary...
I need help to make the script work in which the houses are generated as well as the planes do, they should only be showed when the player is nearby
---Relevant Lines---
(Endless City)
calling updateChunk function in update()(updateChunk/building function is in GenerateBuilding script)
public void UpdateBuildings()
{
for (int i = 0; i < buildingObjects.Count; i++)
{
buildingObjects[i].SetVisible(false);
}
buildingObjects.Clear();
}
adding to dictionary line 68-80(UpdateVisibleChunks function)
if (building.cityChunkDictionary.ContainsKey(viewedChunkCoord))
{
building.cityChunkDictionary[viewedChunkCoord].UpdateCityChunk(viewerPosition, viewedChunkCoord, chunkSize, maxViewDst);
if (building.cityChunkDictionary[viewedChunkCoord].IsVisible())
{
building.buildingObjects.Add(building.cityChunkDictionary[viewedChunkCoord]);
}
}
else
{
building.AddTest(viewedChunkCoord, chunkSize);
}
EndlessCity, CityChunk class
CityChunk function, sending position to GenerateBuilding script to instantiate buildings in right position.
building.requestBuildingSquad(positionV3);
GenerateBuilding relevant lines
builderH function, instantiates the buildings
public float builderH(GameObject[] obj, float Height, Vector3 position)
{
Transform objTrans = obj[Random.Range(0, obj.Length)].transform;
//Instantiate house Object
GameObject objekt = Instantiate(objTrans.gameObject, position + new Vector3(xOfsset * spaceBetween, Height, zOfsset * spaceBetween), transform.rotation);
float height = Test.transform.localScale.y;
objectsss.Add(objekt);
return height;
}
AddTest function, adds instantiates objects from builderH to a dictionary
public void AddTest(Vector2 viewedChunkCoord, float chunkSize)
{
for (int i = 0; i < objectsss.Count; i++)
{
cityChunkDictionary.Add(viewedChunkCoord, new Testing(objectsss[i]));
}
}
Testing class, testing function, adds objects to class
public Testing(GameObject obj)
{
MeshObject = obj;
}
that should be all relevant lines
full scripts(really similar)
EndlessCity Script(this scripts generates the planes and gives position for GenerateBuilding script)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class EndlessCity : MonoBehaviour
{
public const float maxViewDst = 10;
public Transform viewer;
private GenerateBuilding building;
public static Vector2 viewerPosition;
int chunkSize;
int chunksVisibleInViewDst;
Dictionary<Vector2, CityChunk> terrainChunkDictionary = new Dictionary<Vector2, CityChunk>();
List<CityChunk> terrainChunksVisibleLastUpdate = new List<CityChunk>();
void Start()
{
chunkSize = 8 - 1;
chunksVisibleInViewDst = Mathf.RoundToInt(maxViewDst / chunkSize);
}
void Update()
{
viewerPosition = new Vector2(viewer.position.x, viewer.position.z);
UpdateVisibleChunks();
}
void UpdateVisibleChunks()
{
building = FindObjectOfType<GenerateBuilding>();
building.UpdateBuildings();
for (int i = 0; i < terrainChunksVisibleLastUpdate.Count; i++)
{
terrainChunksVisibleLastUpdate[i].SetVisible(false);
}
terrainChunksVisibleLastUpdate.Clear();
int currentChunkCoordX = Mathf.RoundToInt(viewerPosition.x / chunkSize);
int currentChunkCoordY = Mathf.RoundToInt(viewerPosition.y / chunkSize);
for (int yOffset = -chunksVisibleInViewDst; yOffset <= chunksVisibleInViewDst; yOffset++)
{
for (int xOffset = -chunksVisibleInViewDst; xOffset <= chunksVisibleInViewDst; xOffset++)
{
Vector2 viewedChunkCoord = new Vector2(currentChunkCoordX + xOffset, currentChunkCoordY + yOffset);
if (terrainChunkDictionary.ContainsKey(viewedChunkCoord))
{
terrainChunkDictionary[viewedChunkCoord].UpdateTerrainChunk();
if (terrainChunkDictionary[viewedChunkCoord].IsVisible())
{
terrainChunksVisibleLastUpdate.Add(terrainChunkDictionary[viewedChunkCoord]);
}
}
else
{
terrainChunkDictionary.Add(viewedChunkCoord, new CityChunk(viewedChunkCoord, chunkSize, transform));
}
if (building.cityChunkDictionary.ContainsKey(viewedChunkCoord))
{
building.cityChunkDictionary[viewedChunkCoord].UpdateCityChunk(viewerPosition, viewedChunkCoord, chunkSize, maxViewDst);
if (building.cityChunkDictionary[viewedChunkCoord].IsVisible())
{
building.buildingObjects.Add(building.cityChunkDictionary[viewedChunkCoord]);
}
}
else
{
building.AddTest(viewedChunkCoord, chunkSize);
}
}
}
}
public class CityChunk
{
private GenerateBuilding building;
public GameObject meshObject;
public Vector3 positionV3;
Vector2 position;
Bounds bounds;
public CityChunk(Vector2 coord, int size, Transform parent)
{
building = FindObjectOfType<GenerateBuilding>();
position = coord * size;
bounds = new Bounds(position, Vector2.one * size);
positionV3 = new Vector3(position.x, 0, position.y);
int xPosition = building.xLength / 2;
int zPosition = building.zLength / 2;
float xOfsset = building.xOfsset;
float zOfsset = building.zOfsset;
float spaceBetween = building.spaceBetween;
//Instantiate plane
meshObject = Instantiate(building.groundObject, positionV3 + new Vector3((xPosition + xOfsset) * spaceBetween, -.5f, (xPosition + 1 + zOfsset) * spaceBetween), Quaternion.identity);
SetVisible(false);
building.requestBuildingSquad(positionV3);
}
public void UpdateTerrainChunk()
{
float viewerDstFromNearestEdge = Mathf.Sqrt(bounds.SqrDistance(viewerPosition));
bool visible = viewerDstFromNearestEdge <= maxViewDst;
SetVisible(visible);
}
public void SetVisible(bool visible)
{
meshObject.SetActive(visible);
}
public bool IsVisible()
{
return meshObject.activeSelf;
}
}
}
GenerateBuilding(this script generates Buildings on the planes)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateBuilding : MonoBehaviour
{
public int minHeight = 2;
public int maxHeight = 8;
public int cubeTileX;
public int cubeTileZ;
public int xLength;
public int zLength;
public float spaceBetween;
public float xOfsset;
public float zOfsset;
public GameObject TesObject;
public GameObject[] Base;
public GameObject[] secondB;
public GameObject[] roof;
public GameObject groundObject;
public List<GameObject> objectsss;
public Dictionary<Vector2, Testing> cityChunkDictionary = new Dictionary<Vector2, Testing>();
public List<Testing> buildingObjects = new List<Testing>();
public GameObject Test;
void Start()
{
//requestBuildingSquad(this.transform.position);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
//
}
}
public void requestBuildingSquad(Vector3 position)
{
//*getting the middle of the city squad
int xPosition = xLength / 2;
int zPosition = zLength / 2;
//*
for (int z = 0; z < zLength; z++)
{
zOfsset++;
for (int x = 0; x < xLength; x++)
{
GenerateBuildings(position);
}
xOfsset = 0;
}
zOfsset = 0;
}
public void GenerateBuildings(Vector3 position)
{
int bHeight = Random.Range(minHeight, maxHeight);
float bOfsset = 0;
bOfsset += builderH(Base, bOfsset, position);
for (int i = 0; i < bHeight; i++)
{
bOfsset += builderH(secondB, bOfsset, position);
}
bOfsset += builderH(roof, bOfsset, position);
xOfsset++;
}
public float builderH(GameObject[] obj, float Height, Vector3 position)
{
Transform objTrans = obj[Random.Range(0, obj.Length)].transform;
//Instantiate house Object
GameObject objekt = Instantiate(objTrans.gameObject, position + new Vector3(xOfsset * spaceBetween, Height, zOfsset * spaceBetween), transform.rotation);
float height = Test.transform.localScale.y;
objectsss.Add(objekt);
return height;
}
public void AddTest(Vector2 viewedChunkCoord, float chunkSize)
{
for (int i = 0; i < objectsss.Count; i++)
{
cityChunkDictionary.Add(viewedChunkCoord, new Testing(objectsss[i]));
}
}
public void UpdateBuildings()
{
for (int i = 0; i < buildingObjects.Count; i++)
{
buildingObjects[i].SetVisible(false);
}
buildingObjects.Clear();
}
public class Testing
{
public GameObject MeshObject;
Vector2 position;
Bounds bounds;
public Testing(GameObject obj)
{
MeshObject = obj;
}
public void SetVisible(bool visiblee)
{
MeshObject.SetActive(visiblee);
}
public bool IsVisible()
{
return MeshObject.activeSelf;
}
public void UpdateCityChunk(Vector3 viewerPosition, Vector2 coord, int size, float maxViewDst)
{
position = coord * size;
bounds = new Bounds(position, Vector2.one * size);
float viewerDstFromNearestEdge = Mathf.Sqrt(bounds.SqrDistance(viewerPosition));
bool visible = viewerDstFromNearestEdge <= maxViewDst;
SetVisible(visible);
}
}
}
The problem is that you are trying to add twice elements with the same key.
here is the documentation of the Add method for dictionaries, and as it states, trying to add an existing key throws an error.
You can either use the TryAdd method, which adds an item only if the key doesn't exist already in the dictionary, or update the value with the existing key as you can see here.

unity Scriptable object not working in bulid

hi I am new to unity and C# and I am making my first game. In it I have a Scriptable object named "sss".It contains values like coins,speed,jump power. It works fine in the editor but after I build it it wont work.what I mean by it wont work is after the player dies in the game depending on how long they live they will get a certain amount of coins when they go to the store they will see those coins displayed as a UI and they can spend them on things like speed and jump boost. this works in the editor but not in a build. Dose anybody know why this is? here is the code I have in my Scriptable object
using UnityEngine;
[CreateAssetMenu(fileName = "data",menuName = "sss",order = 1)]
public class sss : ScriptableObject
{
public float coins = 0f;
public float speed = 10f;
public float jump = -9.81f;
public bool set = true;
public int face = 1;
}
here is the code I use to display the coins float
coinstext.text = sss.coins.ToString();
and here is the whole store-manager script used to buy stuff
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Security;
using UnityEngine;
using UnityEngine.UI;
public class storemanager : MonoBehaviour
{
public sss sss;
public Text coinstext;
public Slider sliders;
public Slider sliderj;
public int maxcap = 30;
public int maxcapj = 500;
public void Start()
{
coinstext.text = sss.coins.ToString();
}
public void speedbuy()
{
if (sss.coins >= 5 && sss.speed < maxcap)
{
sss.speed += 1;
sss.buyspeed = true;
sss.coins -= 5;
sliders.value += 1;
coinstext.text = sss.coins.ToString();
}
}
public void jumpbuy()
{
if (sss.coins >= 7 && sss.jump < maxcapj)
{
sss.jump += 10;
sss.buyjump = true;
sss.coins -= 7;
sliderj.value += 10;
coinstext.text = sss.coins.ToString();
}
}
}
While changes in ScriptableObject within the UnityEditor are persistent, they are not persistent in a build!
When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting. In a deployed build, however, you can’t use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.
So after a build the data in the asset is kind of baked and you can change it at runtime but when restarting the app you will always re-load the data of the build.
You would need to store your data instead in a local file stored on the device itself e.g. using Json like
using UnityEngine;
using System.IO;
...
public class sss : ScriptableObject
{
public float coins = 0f;
public float speed = 10f;
public float jump = -9.81f;
public bool set = true;
public int face = 1;
private const string FILENAME = "sss.dat";
public void SaveToFile()
{
var filePath = Path.Combine(Application.persistentDataPath, FILENAME);
if(!File.Exists(filePath))
{
File.Create(filePath);
}
var json = JsonUtility.ToJson(this);
File.WriteAllText(filePath, json);
}
public void LoadDataFromFile()
{
var filePath = Path.Combine(Application.persistentDataPath, FILENAME);
if(!File.Exists(filePath))
{
Debug.LogWarning($"File \"{filePath}\" not found!", this);
return;
}
var json = File.ReadAllText(filePath);
JsonUtility.FromJsonOverwrite(json, this);
}
}
And then in your manager script call the load and save methods e.g.
public class storemanager : MonoBehaviour
{
public sss sss;
public Text coinstext;
public Slider sliders;
public Slider sliderj;
public int maxcap = 30;
public int maxcapj = 500;
public void Start()
{
sss.LoadFromFile();
coinstext.text = sss.coins.ToString();
}
// Called when the application is going to quit
private void OnApplicationQuit()
{
sss.SaveToFile();
}
Note: Typed on smartphone but I hope the idea gets clear

Unity Number Wizard Back Button

I just created a Number Game witch guesses what number you are thinking of and shows it to the screen as a TextMeshProUGUI element. I want to add a back button so that when you press the incorrect button the TextMeshProUGUI element displays the value that was displayed before the user pressed the incorrect button.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour {
[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;
int guess;
// Use this for initialization
void Start ()
{
StartGame();
}
void StartGame()
{
NextGuess();
}
public void OnPressHigher()
{
min = guess + 1;
NextGuess();
}
public void OnPressLower()
{
max = guess - 1;
NextGuess();
}
void NextGuess()
{
guess = Random.Range(min, max+1);
guessText.text = guess.ToString();
}
public void Back()
{
//Back code should go here
}
}
Scene View
you just have to remember the last guess:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour {
[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;
int guess;
int lastGuess;
int lastMin;
int lastMax;
// Use this for initialization
void Start ()
{
StartGame();
}
void StartGame()
{
NextGuess();
}
public void OnPressHigher()
{
lastMin = min;
min = guess + 1;
NextGuess();
}
public void OnPressLower()
{
lastMax = max;
max = guess - 1;
NextGuess();
}
void NextGuess()
{
lastGuess = guess;
guess = Random.Range(min, max+1);
guessText.text = guess.ToString();
}
public void Back()
{
guess = lastGuess;
min = lastMin;
max = lastMax;
guessText.text = guess.ToString();
}
}
if this is not what you want, please write a comment and i will edit the answer

How can i export my void update transform variables to a json file

using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
public class Rotator : MonoBehaviour {
public Character player = new Character(0, 0, 0, 0,0);
// Use this for initialization
JsonData playerJson;
i want to be able to change the values from a json file of the rotating obstracles that i will add to my game but i cant possibly find a way to do this since i am very new to json files,so how can i add the values of the public class character within the void update or at least a way to just parse the variables for the rotation.
In more detail and in simpler words the void update is supposed to rotate the object as in the values you see inside but i want to export these values to a json file and for them to be changable within the json file so can you please help me out? its very important
void Start()
{
playerJson = JsonMapper.ToJson(player);
File.WriteAllText(Application.dataPath + "/Player.json", playerJson.ToString());
}
public int Xaxis;
public int Yaxis;
public int Zaxis;
public int speed;
void Update()
{
transform.Rotate(new Vector3(Xaxis, Yaxis, Zaxis) * Time.deltaTime *speed);
}
public class Character
{
public int id;
public int Xaxis;
public int Yaxis;
public int Zaxis;
public int speed;
public Character(int id, int Xaxis, int Yaxis, int Zaxis, int speed)
{
this.id = id;
this.Xaxis = Xaxis;
this.Yaxis = Yaxis;
this.Zaxis = Zaxis;
this.speed = speed;
}
}
}

Categories

Resources