Why does my element not move until it hits something? Unity - c#

I want to make my element move until it hits something when i swipe.
I got following Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System;
public class PlayerController : MonoBehaviour
{
IEnumerator OnSwipeUp()
{
if(!isCurrentlyColliding)
{
transform.Translate(0,0.5f,0);
yield return null;
}else{
StopCoroutine(OnSwipeUp());
}
}
IEnumerator OnSwipeDown()
{
if(!isCurrentlyColliding)
{
transform.Translate(0,-0.5f,0);
yield return null;
}else{
StopCoroutine(OnSwipeUp());
}
}
IEnumerator OnSwipeLeft()
{
if(!isCurrentlyColliding)
{
transform.Translate(-0.5f,0,0);
yield return null;
}else{
StopCoroutine(OnSwipeUp());
}
}
IEnumerator OnSwipeRight()
{
if(!isCurrentlyColliding)
{
transform.Translate(0.5f,0,0);
yield return null;
}else{
StopCoroutine(OnSwipeUp());
}
}
bool isCurrentlyColliding = false;
void OnCollisionEnter2D(Collision2D col) {
isCurrentlyColliding = true;
}
void OnCollisionExit2D(Collision2D col) {
isCurrentlyColliding = false;
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
private Vector2 fingerDown;
private Vector2 fingerUp;
public float SWIPE_THRESHOLD = 20f;
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
StartCoroutine(OnSwipeUp());
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
StartCoroutine(OnSwipeDown());
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
StartCoroutine(OnSwipeRight());
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
StartCoroutine(OnSwipeLeft());
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
}
But it only moves one "Field" and it also doesn't stop if it collides with something. My Player has a 2D Box Collider and my Walls too. Do i need a Rigidbody or what? I used coroutines so it could check if it collides. Before i had while loops which stopped the code from executing further. I would be happy if you could help me.

Related

Unity PUN 2 shooting not syncing

I wanted to add multiplayer to my game but i quickly faced many many problems, i cant find any clear solution online. i made a weapon script where the player can shoot and reload.
problems:
when i shoot, on 1 screen both players shoot, but at the other screen nothing happens
when i swap weapons, on 1 screen both players swap weapons, on the second screen nothing happens
note: im still a complete beginner so go easy on me please :)) thanks!
weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Photon.Pun;
public class weaponScript : MonoBehaviour
{
public weaponSO weaponStats;
public GameObject reloadingText;
public TMP_Text ammoValue;
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 2f;
public bool isShooting;
public float pistolDamage;
public int currentAmmoClip = 1;
public int maxAmmoClip;
public int currentReserve = 1;
public int maxReserve;
public float reloadTime = 2f;
public bool isReloading = false;
public int bulletsShot;
public float startingDamage;
PhotonView view;
public void Start()
{
view = GetComponent<PhotonView>();
if(view.IsMine)
{
view.RPC("Update", RpcTarget.AllBuffered);
}
WeaponStats();
currentAmmoClip = maxAmmoClip;
currentReserve = maxReserve;
bulletsShot = maxAmmoClip - currentAmmoClip;
isShooting = false;
weaponStats.damage = startingDamage;
}
[PunRPC]
public void Update()
{
ammoValue.text = currentAmmoClip.ToString("0") + "/" + currentReserve.ToString("0");
if (Input.GetKeyDown(KeyCode.R))
{
if(currentReserve <= 0)
{
return;
}
if (currentAmmoClip == maxAmmoClip && !isReloading)
{
return;
}
else
{
StartCoroutine(Reload());
return;
}
}
if(Input.GetButtonDown("Fire1") && currentAmmoClip >= 1)
{
if(isReloading == false)
{
bulletsShot += 1;
currentAmmoClip -= 1;
isShooting = true;
Shoot();
FindObjectOfType<AudioManager>().Play("shot1");
return;
}
}
if(isReloading)
return;
if(currentAmmoClip <= 0 && currentReserve >= 1)
{
StartCoroutine(Reload());
return;
}
}
IEnumerator Reload()
{
reloadingText.SetActive(true);
isReloading = true;
yield return new WaitForSeconds(reloadTime);
if(currentReserve <= bulletsShot)
{
currentAmmoClip += currentReserve;
currentReserve = 0;
}
else
{
currentReserve -= bulletsShot;
currentAmmoClip = maxAmmoClip;
}
bulletsShot = 0;
reloadingText.SetActive(false);
isReloading = false;
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
public void WeaponStats()
{
pistolDamage = weaponStats.initialDamage;
maxAmmoClip = weaponStats.maxAmmoClip;
maxReserve = weaponStats.maxReserve;
reloadTime = weaponStats.reloadTime;
bulletForce = weaponStats.bulletForce;
startingDamage = weaponStats.initialDamage;
}
}
weapon holder:
using UnityEngine;
public class WeaponHolder : MonoBehaviour
{
public int selectedWeapon = 0;
void Start()
{
SelectWeapon();
}
void Update()
{
if(FindObjectsOfType<weaponScript>()[0].isReloading == true)
{
return;
}
else
{
switchWeapon();
}
}
public void switchWeapon()
{
int previousSelectedWeapon = selectedWeapon;
if(Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if(selectedWeapon >= transform.childCount - 1)
{
selectedWeapon = 0;
}
else
{
selectedWeapon++;
}
}
if(Input.GetAxis("Mouse ScrollWheel") < 0f)
{
if(selectedWeapon <= 0)
{
selectedWeapon = transform.childCount - 1;
}
else
{
selectedWeapon--;
}
}
if(previousSelectedWeapon != selectedWeapon)
{
SelectWeapon();
}
}
public void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if(i == selectedWeapon)
{
weapon.gameObject.SetActive(true);
}
else
{
weapon.gameObject.SetActive(false);
}
i++;
}
}
}
i tried adding
if(view.IsMine == true)
{
Debug.Log("true");
}
else
{
Debug.Log("false");
}
but nothing happened and i couldnt shoot anymore. thanks for reading
The problem is you don't sync anything in your game. This means the other computer can't know what it has to do.
Whenever you want to sync something you have to call an RPC function.
Maybe watch some tutorials about how to do this properly and how to set up a simple multiplayer lobby.
EDIT:
What the other comments above mentioned with .IsMine is true, but you're doing it wrong. You have to call this in start or awake and whenever the view is not yours you disable the camera of the person only and disable shooting. Its important to only do this on your computer! If you are not doing everyone will shoot when you press Shoot and everyone will walk when you walk.

How do I call a method which is in another class, when swiping up, down, left or right? Unity2D

I have a Unity project that I started a couple of days ago. It is a simple 2D top down shooting game, which is aimed to be played on smartphone platforms.
I have a Shooting script, which basically has a method called Shoot1, which spawns in a bullet.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject BulletRedPrefab;
public GameObject BulletGreenPrefab;
public float bulletForce = 20f;
// Update is called once per frame
void Start()
{
}
void Update()
{
}
public IEnumerator Shoot1()
{
yield return new WaitForSeconds(0.00001f);
GameObject bullet = Instantiate(BulletRedPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
I also have the Swipe script which determines the direction of the swipe, etc.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swipe : MonoBehaviour
{
private bool tap, swipeUp, swipeDown, swipeLeft, swipeRight;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
// Update is called once per frame
private void Update()
{
tap = swipeUp = swipeDown = swipeLeft = swipeRight = false;
if (Input.touches.Length > 0)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
{
isDraging = false;
Reset();
}
}
if (Input.GetMouseButtonDown(0))
{
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0))
{
isDraging = false;
Reset();
}
swipeDelta = Vector2.zero;
if (isDraging)
{
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
if (swipeDelta.magnitude > 125)
{
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else
{
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
private void Reset()
{
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
}
And I have the GestureDetector script which is aimed to shoot a bullet whenever the user swipes left, right, up or down. When I tried to make the player object (which is called robot) move via swiping, it worked. But when I try calling a method from another class with swiping, it's not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GestrueDetector : MonoBehaviour
{
public Shooting other;
public Swipe swipeControls;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
if (GameObject.Find("robot") != null)
{
if (swipeControls.SwipeLeft)
desirePosition += Vector3.left;
other.Shoot1();
if (swipeControls.SwipeRight)
desirePosition += Vector3.right;
other.Shoot1();
if (swipeControls.SwipeUp)
desirePosition += Vector3.up;
other.Shoot1();
if (swipeControls.SwipeDown)
desirePosition += Vector3.down;
other.Shoot1();
}
}
}
I just started using unity this week, so I'm quite new to the software. Thank you very much!
For coroutines you need to call this methods like this:
StartCoroutine(Shoot1());
I a little bit changed your classes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject BulletRedPrefab;
public GameObject BulletGreenPrefab;
public float bulletForce = 20f;
void Start ()
{
}
void Update()
{
}
public void Shoot()
{
StartCoroutine(Shoot1());
}
private IEnumerator Shoot1()
{
yield return new WaitForSeconds(0.00001f);
GameObject bullet = Instantiate(BulletRedPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
And for GestrueDetector:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GestrueDetector : MonoBehaviour
{
public Shooting other;
public Swipe swipeControls;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
if (GameObject.Find("robot") != null)
{
if (swipeControls.SwipeLeft)
desirePosition += Vector3.left;
other.Shoot();
if (swipeControls.SwipeRight)
desirePosition += Vector3.right;
other.Shoot();
if (swipeControls.SwipeUp)
desirePosition += Vector3.up;
other.Shoot();
if (swipeControls.SwipeDown)
desirePosition += Vector3.down;
other.Shoot();
}
}
}
Just read more about how coroutines are working in Unity - https://docs.unity3d.com/ScriptReference/Coroutine.html

I have a working swipe detector script, but I don't know how to connect it to my character controller

My game is an endless runner and the character only needs to move along the y-axis. What I want to happen is that the player moves up or down depending on the swipe, and I thought that I could do it by stating that if the player triggered the onSwipeUp or down then they would move in that direction, but I couldn't get it working.
This is the player controller script before I tried implementing swipe controls into it:
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float yIncrement;
public float maxHeight;
public float minHeight;
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.W) && transform.position.y < maxHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
}
else if (Input.GetKeyDown(KeyCode.S) && transform.position.y > minHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
}
}
And this is the swipe detecting script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeTest : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
public void OnSwipeUp()
{
Debug.Log("Swipe UP");
}
public void OnSwipeDown()
{
Debug.Log("Swipe Down");
}
void OnSwipeLeft()
{
Debug.Log("Swipe Left");
}
void OnSwipeRight()
{
Debug.Log("Swipe Right");
}
}
You could set a public boolean for each swipe direction. In the first lines of update set these booleans to false, in the onswipe functions set the respective booleans to true. Then reference the swipetest script from the player script and check if the desired swipe boolean is set to true.
The code would look something like this:
player:
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float yIncrement;
public float maxHeight;
public float minHeight;
public SwipeTest swipetest;
private void OnEnable()
{
swipetest = (SwipeTest)FindObjectOfType(typeof(SwipeTest));
}
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (swipetest.swipeUp && transform.position.y < maxHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y + yIncrement);
}
else if (swipetest.swipeDown && transform.position.y > minHeight)
{
Instantiate(effect, transform.position, Quaternion.identity);
targetPos = new Vector2(transform.position.x, transform.position.y - yIncrement);
}
}
swipetest
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeTest : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;
public bool swipeUp = false;
public bool swipeDown = false;
public bool swipeLeft = false;
public bool swipeRight = false;
// Update is called once per frame
void Update()
{
swipeUp = false;
swipeDown = false;
swipeLeft = false;
swipeRight = false;
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
public void OnSwipeUp()
{
swipeUp = true;
}
public void OnSwipeDown()
{
swipeDown = true;
}
void OnSwipeLeft()
{
swipeLeft = true;
}
void OnSwipeRight()
{
swipeRight = true;
}
}

Controlling swipe inputs in unity

I am practicing in Unity; I want to move an object to the right and left according to how I swipe. I have gotten the script so far but the problem occurs when I am playing it. It is setting the objects location to the center; swipe actions are working just fine. However, I don't want it to set the object to the center.
Script:
public class swipeTest : MonoBehaviour {
public SwipeManager swipeControls;
public Transform Player;
private Vector3 desiredPosition;
private void Update() {
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}
And Another
public class SwipeManager : MonoBehaviour {
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool Tap { get { return tap; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
private void Update() {
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
#region Standalone Inputs
if (Input.GetMouseButtonDown(0)) {
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0)) {
isDraging = false;
Reset();
}
#endregion
#region Mobile Input
if (Input.touches.Length > 0) {
if (Input.touches[0].phase == TouchPhase.Began) {
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled) {
isDraging = false;
Reset();
}
}
#endregion
// Calculate the distance
swipeDelta = Vector2.zero;
if (isDraging) {
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//Did we cross the distance?
if (swipeDelta.magnitude > 125) {
//Which direction?
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y)) {
//Left or right
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else {
// Up or down
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
void Reset() {
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}
}
It seems like you never initialised desiredPosition in your code.
I did not successfully reproduce your issue, but theoretically I believe this should work. Please let us know if it helped.
Assuming no other forces act on the Player tranform (it won't be moved other than by this script):
public class swipeTest : MonoBehaviour {
private void Start() {
desiredPosition = Player.position;
}
}
Or if other forces act on Player you should update it every time:
public class swipeTest : MonoBehaviour {
private void Update() {
desiredPosition = Player.position;
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}

Unity High_Score Badges C#

Hello I want to create badges like in flappy bird , I put images in UI images like GameObjects. But it show me only one image of 3 images Please Please Help Out! And HighScore works , it rewrites when I get Higher score , but don't know why images won't change :(
Sorry For bad english
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
private float score = 0f;
public Text Scoretext;
public MenuController deathmenu;
public GameObject IntroGUI, DeathGUI, Canvas;
public GameObject[] medals;
public GameObject medale;
void Start()
{
medale.SetActive(false);
foreach(GameObject m in medals)
{
m.SetActive(true);
}
}
void Update()
{
//handle back key in Windows Phone
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
if (GameStateManager.GameState == GameState.Intro)
{if (WasTouchedOrClicked())
{
GameStateManager.GameState = GameState.Playing;
IntroGUI.SetActive(false);
Canvas.SetActive(true);
}
}
else if (GameStateManager.GameState == GameState.Playing)
{
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
if(PlayerPrefs.GetFloat("Scoretext") > 0)
{
medals[0].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 2)
{
medals[1].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 5)
{
medals[2].SetActive(true);
}
medale.SetActive(true);
deathmenu.ToggleEndMenu(score);
}
}
In Image you can see my GameObjects and Etc.
I updated the code but still doesnt work
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
private float score = 0f;
public Text Scoretext;
public MenuController deathmenu;
public GameObject IntroGUI, DeathGUI, Canvas;
public GameObject[] medals;
public GameObject medale;
void Start()
{
medale.SetActive(true);
}
void Update()
{
//handle back key in Windows Phone
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
if (GameStateManager.GameState == GameState.Intro)
{
if (WasTouchedOrClicked())
{
GameStateManager.GameState = GameState.Playing;
IntroGUI.SetActive(false);
Canvas.SetActive(true);
medale.SetActive(false);
}
}
else if (GameStateManager.GameState == GameState.Playing)
{
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
deathmenu.ToggleEndMenu(score);
}
}
void FixedUpdate()
{
//just jump up and down on intro screen
if (GameStateManager.GameState == GameState.Intro)
{
}
else if
(GameStateManager.GameState == GameState.Playing || GameStateManager.GameState == GameState.Dead)
{
}
}
bool WasTouchedOrClicked()
{
if (Input.GetButtonUp("Jump") || Input.GetMouseButtonDown(0) ||
(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
return true;
else
return false;
}
void OnCollisionEnter2D(Collision2D col)
{
if (GameStateManager.GameState == GameState.Playing)
{
if (col.gameObject.tag == "CARS")
{
PlayerDies();
}
}
}
void PlayerDies()
{
GameStateManager.GameState = GameState.Dead;
if (PlayerPrefs.GetFloat("Scoretext") > 0)
{
medals[0].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 2)
{
medals[1].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 5)
{
medals[2].SetActive(true);
}
}
}
Turns out the stuff below is not enough to let your stuff work, you need to change medale.SetActive(false); to medale.SetActive(true); because this is the parent object which your medals are in.
You don't set the Scoretext anywhere so look at the score instead of the scoretext.
So you get:
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
if(score > 0)
{
medals[0].SetActive(true);
}
else if
(score > 2)
{
medals[1].SetActive(true);
}
else if
(score > 5)
{
medals[2].SetActive(true);
}
Also, why are you setting them active at the start?

Categories

Resources