I have a canvas with three text objects in unity. i have 4 scenes: Load, Play, Hub, and Tutorial.
I'm using a Script Object that keeps track of your scores as you play. But, every time I set a high score, my text objects still say "1st" "2nd" "3rd." Here's my script: (Also, in play, the text for my score updates, but the (Highscores) is not updating between scenes. And the object the script is on is parenting all except for Camera.Main)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class TrackScores : MonoBehaviour
{
public Transform First;
public Transform Second;
public Transform Third;
public Text Best;
public Text Average;
public Text Worst;
public Text Score;
public Transform ScoreTracker;
public Canvas CanvUI;
public float ScoreInt;
public Vector3 PosPlayer;
void Start()
{
DontDestroyOnLoad(Camera.main.transform.root.gameObject);
DontDestroyOnLoad(transform.root.gameObject);
SceneManager.LoadScene("Hub", LoadSceneMode.Single);
}
void Update()
{
if(SceneManager.GetActiveScene().name == "Play")
{
PosPlayer = new Vector3(GameObject.Find("Player").transform.position.x, GameObject.Find("Player").transform.position.y, 0);
Camera.main.transform.position = PosPlayer + new Vector3(0, 0, -15);
transform.position = new Vector3(0, 0, 1001);
Score = GameObject.Find("Score").GetComponent<Text>();
ScoreTracker = GameObject.Find("ScoreTracker").transform;
ScoreInt = ScoreTracker.position.x * 1000;
Score.text = ScoreInt.ToString("0");
}
if(SceneManager.GetActiveScene().name == "Tutorial")
{
PosPlayer = new Vector3(GameObject.Find("Quad").transform.position.x, GameObject.Find("Quad").transform.position.y, 0);
Camera.main.transform.position = PosPlayer + new Vector3(0, 0, -15);
transform.position = new Vector3(0, 0, -1000);
}
if(SceneManager.GetActiveScene().name == "Hub")
{
Camera.main.transform.position = new Vector3(0, 0, -25);
transform.position = new Vector3(0, 0, 0);
Best.text = "1st: " + First.position.x.ToString("0");
Average.text = "2nd: " + Second.position.x.ToString("0");
Worst.text = "3rd:" + Third.position.x.ToString("0");
if(ScoreInt < Second.position.x && ScoreInt > Third.position.x)
{
Third.position = new Vector3(ScoreInt, 0, 0);
}
if(ScoreInt < First.position.x && ScoreInt > Second.position.x)
{
Second.position = new Vector3(ScoreInt, 0, 0);
}
if(ScoreInt > First.position.x)
{
First.position = new Vector3(ScoreInt, 0, 0);
}
}
}
}
Any help is appreciated!
I figured it out. i just need to use text mesh with TextMesh UI.
Related
I've just started learning Unity, and I wanted to try to write a Snake.
Logic goes as follows:
Head marks its spot
Head moves
Loop starts
Child goes to marked spot
Spot where child was gets marked
This should have made elements of the snake follow each other, however, it results in weird shapes:
Here's snake's starting position
And here is snake's position after pressing "w"
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
public class Movement : MonoBehaviour
{
int fps = 60;
Vector3 prev_pos, mark_pos;
void Start()
{
Application.targetFrameRate = fps;
}
void Update_child()
{
foreach(Transform child in transform)
{
prev_pos = child.position;
child.position = mark_pos;
mark_pos = prev_pos;
print(child.position);
print(child.name);
}
}
void Update()
{
mark_pos = transform.position;
if (Input.GetKeyDown("w"))
{
transform.position += new Vector3(0, 1, 0);
Update_child();
}
else if (Input.GetKeyDown("a"))
{
transform.position += new Vector3(-1, 0, 0);
Update_child();
}
else if (Input.GetKeyDown("s"))
{
transform.position += new Vector3(0, -1, 0);
Update_child();
}
else if (Input.GetKeyDown("d"))
{
transform.position += new Vector3(1, 0, 0);
Update_child();
}
}
}
I firstly want to understand the mistake, not to get the fixed version of the code, if someone could explain the error, I would appreciate it.
I tried doing this with relative and absolute postions, as both of them are used, but to no avail.
Your answer was almost correct but in your hierarchy you make the tail a children of the head and in Unity, when you move a parent, all of the children move too. To fix your issue, uncouple the tail and track the transforms.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
int fps = 60;
Vector3 prev_pos, mark_pos;
[Header("The head of the snake")]
[SerializeField] Transform headTransform;
[Header("The tail of the snake")]
[SerializeField] Transform[] transforms;
void Start()
{
Application.targetFrameRate = fps;
}
void Update_child()
{
foreach (Transform child in transforms)
{
prev_pos = child.position;
child.position = mark_pos;
mark_pos = prev_pos;
print(child.position);
print(child.name);
}
}
void Update()
{
mark_pos = headTransform.position;
if (Input.GetKeyDown("w"))
{
headTransform.position += new Vector3(0, 1, 0);
Update_child();
}
else if (Input.GetKeyDown("a"))
{
headTransform.position += new Vector3(-1, 0, 0);
Update_child();
}
else if (Input.GetKeyDown("s"))
{
headTransform.position += new Vector3(0, -1, 0);
Update_child();
}
else if (Input.GetKeyDown("d"))
{
headTransform.position += new Vector3(1, 0, 0);
Update_child();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLines : MonoBehaviour
{
public LineRenderer lineRenderer;
public GameObject dotPrefab;
public string numbers;
private Vector3[] Positions;
// Start is called before the first frame update
void Start()
{
DrawNumber(0);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown("0"))
{
DrawNumber(0);
numbers = "0";
}
}
void DrawNumber(int number)
{
if (number == 0)
{
Zero();
}
}
private void Zero()
{
Positions = new Vector3[7] { new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(1, -1, 0),
new Vector3(1,-2,0),
new Vector3(0,-2,0),
new Vector3(0,-1,0),
new Vector3(0,0,0)};
lineRenderer.positionCount = 7;
lineRenderer.SetPositions(Positions);
for (int i = 0; i < Positions.Length; i++)
{
var dot = Instantiate(dotPrefab);
dot.transform.position = Positions[i];
}
}
}
Each time I press on the key 0 it's creating another Zero but the first problem is that the new zero is on the same positions of the first zero so I want to put all the Zeros under a parent so each time I press on 0 it will create a new Zero gameobject child and also the new child will be in a bit different position.
I think thats what you'r looking for.
private const float LETTER_WIDTH = 2f;
public LineRenderer lineRenderer;
public GameObject dotPrefab;
public string numbers;
public Transform WordAnchor;//parent object to set all the letters under
private int currentLetterIndex = 0;
private Vector3[] Positions;
// Start is called before the first frame update
void Start()
{
DrawNumber(0);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown("0"))
{
DrawNumber(0);
numbers = "0";
}
}
void DrawNumber(int number)
{
if (number == 0)
{
Zero();
}
}
private void Zero()
{
Positions = new Vector3[7] { new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(1, -1, 0),
new Vector3(1,-2,0),
new Vector3(0,-2,0),
new Vector3(0,-1,0),
new Vector3(0,0,0)};
//Create a gameobject to parent the dots under
GameObject letter = new GameObject(currentLetterIndex.ToString() );
letter.transform.parent = WordAnchor;//parent the letter under the word
letter.transform.localPosition = new Vector3(currentLetterIndex * LETTER_WIDTH, 0f, 0f);//move an offset base on the index
LineRenderer lineRendererInstance = letter.AddComponent<LineRenderer>();
lineRendererInstance.positionCount = 7;
lineRendererInstance.SetPositions(Positions);
lineRendererInstance.useWorldSpace = false;
for (int i = 0; i < Positions.Length; i++)
{
var dot = Instantiate(dotPrefab, letter.transform);//parent the dot under the letter.
dot.transform.localPosition = Positions[i];//set the relative position.
}
++currentLetterIndex;
}
So far I'm making an app, and the early stages of it will just be a fish swimming around a small box. I made code that alters the fishes direction randomly and if it reaches certain x or y values to keep it within visibility of the camera. Unfortunately my C# knowledge is limited and I can't figure out how to make it turn the direction it is , this is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishBehavior : MonoBehaviour {
public float speed = 2f;
float moveSpeed = 0f;
private Rigidbody2D rigid;
public float rotateSpeed = 2f;
public bool isPredator = false;
void Start () {
rigid = GetComponent<Rigidbody2D>();
rigid.velocity = new Vector2(speed, 0);
InvokeRepeating("FishMovement", 3f, Random.Range(2f,6f));
}
// Update is called once per frame
void Update () {
int num = Random.Range(1, 10);
if (transform.position.x >= 11.5)
{
speed = -2;
rigid.velocity = new Vector2(speed, 0);
}
if (transform.position.x <= -11.5)
{
speed = 2;
rigid.velocity = new Vector2(speed, 0);
}
if (transform.position.y >= 5.07)
{
rigid.velocity = new Vector2(Random.Range(-2, 2), -2);
}
if (transform.position.y <= -4.65)
{
rigid.velocity = new Vector2(Random.Range(-2, 2), 2);
}
}
void FishMovement()
{
int fishSpeed = Random.Range(-3, 3);
if (fishSpeed != 0)
{
moveSpeed = Random.Range(-2, 2);
rigid.velocity = new Vector2(fishSpeed, moveSpeed);
}
}
}
Anything helps thanks
using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour {
private int SphereCount = 20;
private float SphereSize = 10.0f;
private Vector3 pos1 = new Vector3(-4,0,0);
private Vector3 pos2 = new Vector3(4,0,0);
public float speed = 5.0f;
// Use this for initialization
void Start () {
var withTag = GameObject.FindWithTag("Terrain");
if (withTag == null)
throw new InvalidOperationException("Terrain not found");
for (var i = 0; i < SphereCount; i++) {
var o = GameObject.CreatePrimitive (PrimitiveType.Sphere);
o.tag = "Sphere";
o.transform.localScale = new Vector3 (SphereSize, SphereSize, SphereSize);
o.transform.position = new Vector3 (i + 20, 1, 1);
}
}
// Update is called once per frame
void Update () {
/*foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]) {
if (go.name == "Sphere") {
go.transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong (Time.time * speed, 1.0f));
}
}*/
}
}
The first thing I can't figure out is how to create the Spheres on the Terrain in more spread area with spaces between each Sphere? It's making them in specific place in a row one near the other one.
The second part is in the Update function if I will use this code I will see only one Sphere and it will move from side to side but only one. All the rest of the Spheres are gone.
I have a cube that bounces forward and each time that it goes forwards more ground is added. What I want is to make it so that each time the player bounces further forward the ground that the player has past and can no longer see is destroyed. However I am not sure how to do this. Here is my code so far:
using UnityEngine;
using System.Collections;
public class Generation : MonoBehaviour {
public GameObject Water;
public GameObject Road;
public GameObject Grass;
int firstRand;
int secondRand;
int disPlayer = 1;
Vector3 intPos = new Vector3(0, 0, 0);
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("up")) {
firstRand = Random.Range (1, 4);
if (firstRand == 1) {
secondRand = Random.Range (1, 5);
for (int i = 0; i < secondRand; i++) {
intPos = new Vector3 (0, 0, disPlayer + 3);
disPlayer+=3;
GameObject GrassIns = Instantiate (Grass) as GameObject;
GrassIns.transform.position = intPos;
}
}
if (firstRand == 2) {
secondRand = Random.Range (1, 5);
for (int i = 0; i < secondRand; i++) {
intPos = new Vector3 (0, 0, disPlayer + 3);
disPlayer+=3;
GameObject RoadIns = Instantiate (Road) as GameObject;
RoadIns.transform.position = intPos;
}
}
if (firstRand == 3) {
secondRand = Random.Range (1, 5);
for (int i = 0; i < secondRand; i++) {
intPos = new Vector3 (0, 0, disPlayer + 3);
disPlayer+=3;
GameObject WaterIns = Instantiate (Water) as GameObject;
WaterIns.transform.position = intPos;
}
}
}
}
}
The most simple solution would be to add a game object with a collider as a child of your player. Place it behind enough out of viez so that when the platform enters the collider, you destroy it and it does not show.