Duplicate code but make the copied slower - c#

I build the shooting game by C# and Unity.
I use GameController and GameStatus to show the score and time.
At first scene, I have no problem. It can run smoothly.
But the second scene, I copy scene from first and make new GameController for second scene.
It's work but running game slower.
I try to make new project by using same code, but it's slow even it's my first scene.
I don't know cause of this happen.
Below is my code, it's work.
using UnityEngine;
using System.Collections;
public class MyGameController2 : MonoBehaviour
private Gun gun;
public GUISkin mySkin2;
private GameStatus gameStatus;
public float countDownTime2;
private float scoreTime2;
private float menuTime2;
// Use this for initialization
void Start () {
countDownTime2 = 60.0f;
scoreTime2 = countDownTime2+3;
menuTime2 = countDownTime2+5;
gameStatus = (GameStatus)GetComponent(typeof(GameStatus));
}
// Update is called once per frame
void Update () {
countDownTime2 -= Time.deltaTime;
if(gameStatus.score >= 300){Application.LoadLevel("MainScene2");}
if(countDownTime2 <= 0.0f)
{gameStatus.isGameOver = true;
countDownTime2 = 0.0f;
gameStatus.score +=0;
}
scoreTime2 -= Time.deltaTime;
menuTime2 -= Time.deltaTime;
}
void OnGUI()
{
float sw = Screen.width;
float sh = Screen.height;
GUI.skin = mySkin2;
int mScore = gameStatus.score;
if(countDownTime2 > 0.0f){
GUI.Label (new Rect(50,0,sw/2,sh/2), "Score : " + mScore.ToString(),"scoreStyle");
GUI.Label (new Rect(400,0,0,0), "Time : " + countDownTime2.ToString("000") ,"timeStyle");
}
if(gameStatus.isGameOver)
{GUI.Label (new Rect(120,100,sw/2,sh/4),"Game Over","messageStyle");}
if (scoreTime2 <= 0.0f)
{
GUI.Label (new Rect(130,50,0,0), "Your Score is " + mScore.ToString(),"scoreStyle2");
}
if(menuTime2 <= 0.0f){
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if(GUI.Button(new Rect(100,220,80,20), "Retry")) {
Application.LoadLevel("MainScene");}
if(GUI.Button(new Rect(300,220,80,20), "Menu")) {
Application.LoadLevel("TitleScene");}
}
}
}

Related

How to stop Timer when count equals 12

I am working through the unity tutorials and I was wondering how to stop a timer when you hit 12 of count.
I currently have two scripts I am using.
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
public class PlayerController : MonoBehaviour
{
public float speed;
public TextMeshProUGUI countText;
public GameObject winTextObject;
private float movementX;
private float movementY;
private Rigidbody rb;
private int count;
// At the start of the game..
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winTextObject.SetActive(false);
}
void FixedUpdate()
{
// Create a Vector3 variable, and assign X and Z to feature the horizontal and vertical float variables above
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
// ..and if the GameObject you intersect has the tag 'Pick Up' assigned to it..
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
// Add one to the score variable 'count'
count = count + 1;
// Run the 'SetCountText()' function (see below)
SetCountText();
}
if (other.gameObject.CompareTag("SpeedPickup"))
{
other.gameObject.SetActive(false);
speed = speed + 25;
count = count + 1;
}
}
void OnMove(InputValue value)
{
Vector2 v = value.Get<Vector2>();
movementX = v.x;
movementY = v.y;
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
winTextObject.SetActive(true);
}
}
}
And a second script Timer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Timer : MonoBehaviour
{
[SerializeField]
private TextMeshProUGUI timerUILabel; //drag UI Text object here via Inspector
private float t_offset = 0f; // set to nothing, can be set to an offset if needed.
private int t_minutes;
private int t_seconds;
private int t_milliseconds;
private bool finished = false;
private void Update()
{
float t = Time.time - t_offset;
//Debug.Log("currentTime in seconds = " + t);
t_minutes = ((int)t / 60); // t(seconds) / 60 = total minutes
t_seconds = ((int)t % 60); // t(seconds) % 60 = remaining seconds
t_milliseconds = ((int)(t * 100)) % 100; // (total seconds * 1000) % 1000 = remaining milliseconds
//display the text in a 00:00:00 format
timerUILabel.text = string.Format("{0:00}:{1:00}:{2:00}", t_minutes, t_seconds, t_milliseconds);
}
}
My questions are
Do I need to import the Timer.cs script into the PlayerController to get this functionality to work? If so how? (is it as simple as using a using statement?)
I am thinking I need to put in an additional conditional to change the win condition from false to true. Is that the right path?
Thanks for all your help!
Why not use a coroutine?
private int _time;
private Coroutine _cr;
void Start ()
{
//Call this to start it and save coroutine to a variable
_cr = StartCoroutine(Timer());
//Then to stop it call:
//StopCoroutine(_cr);
//And read the value of _time to get seconds since start.
}
private IEnumerator Timer ()
{
yield return new WaitForSeconds(1);
_time++;
_cr = StartCoroutine(Timer());
}

Unity Snake Game, how to make the body follow the head?

So I've been making a small game to do with Snake, and I'm struggling as to how I can make the Snake's Body appear and follow the position of the head whenever the snake's head touches the apple. I've managed to get the Snake's body to spawn but I can't get it to follow the head correctly. Can anyone help me and tell me how I can do this? Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snake_Move : MonoBehaviour
{
// variables
public Vector2 pos;
private Vector2 moveDirection;
private float moveTimer;
private float timerSeconds;
//Function which runs once when the program starts
void Start()
{
timerSeconds = 0.0167f;
moveTimer = timerSeconds;
moveDirection = new Vector2(0.1f, 0);
}
//Function which updates itself based on your refresh rate
public void Update()
{
AutoMove();
ChangeDirection();
transform.position = new Vector2(pos.x, pos.y);
transform.eulerAngles = new Vector3(0, 0, AngleCalculator(moveDirection) - 90);
}
//Moves the snake 60 units each second
private void AutoMove()
{
moveTimer += Time.deltaTime;
if (moveTimer > timerSeconds)
{
pos += moveDirection;
moveTimer -= timerSeconds;
}
}
//Changes direction of the snake based on arrow key pressed
private void ChangeDirection()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (moveDirection.y != -0.1f)
{
moveDirection.x = 0;
moveDirection.y = 0.1f;
}
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
if (moveDirection.y != 0.1f)
{
moveDirection.x = 0;
moveDirection.y = -0.1f;
}
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
if (moveDirection.x != -0.1f)
{
moveDirection.y = 0;
moveDirection.x = 0.1f;
}
}
else if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if (moveDirection.x != 0.1f)
{
moveDirection.y = 0;
moveDirection.x = -0.1f;
}
}
}
//Calculates the angle at which the snake is moving; used to calculate rotation of sprite
private float AngleCalculator(Vector2 direction)
{
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
return angle;
}
private void SnakeBodySprite()
{
GameObject snakeApple = GameObject.Find("SnakeApple");
Apple_RandomSpawn appleScript = snakeApple.GetComponent<Apple_RandomSpawn>();
//something here?????
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Apple_RandomSpawn : MonoBehaviour
{
private Vector2 foodPos;
void Start()
{
SpawnApple();
}
void Update()
{
transform.position = new Vector2(foodPos.x, foodPos.y);
SnakeAte();
}
public void SpawnApple()
{
foodPos = new Vector2(Random.Range(-17, 17), Random.Range(-9, 9));
}
public void SnakeAte()
{
GameObject snakeBody = GameObject.Find("SnakeBody");
GameObject snakeHead = GameObject.Find("SnakeHead");
Snake_Move snakeMove = snakeHead.GetComponent<Snake_Move>();
if (foodPos.x <= snakeMove.pos.x + 1 &&
foodPos.x >= snakeMove.pos.x - 1 &&
foodPos.y <= snakeMove.pos.y + 1 &&
foodPos.y >= snakeMove.pos.y -1)
{
SpawnApple();
Instantiate(snakeBody);
}
}
}
This is kind of a broad question, so it's hard to answer completely. The thought that comes to my mind is using a Queue of move Vectors for the head, and then applying those movements to the body. You would need a reference to the snake body object, and need to know how many movements the head is from the body. It looks like that might be 60 in your case.
I would add the Queue in this section:
Queue<Vector2> moveDirections = new Queue<Vector2>();
SnakeBody snakeBody; // Reference to 1st snake body element
float offset = 60; // ?
private void AutoMove()
{
moveTimer += Time.deltaTime;
// enqueue the most recent moveDirection
moveDirections.Enqueue(moveDirection);
if (moveTimer > timerSeconds)
{
pos += moveDirection;
moveTimer -= timerSeconds;
// Get oldest moveDirection from the head to apply to the body
Vector2 bodyMovement = moveDirections.Dequeue();
snakeBody.transform.Translate(bodyMovement);
}
// If the queue count is greater than how far ahead the head should be from the
// first body element, remove one from queue.
if (moveDirections.Count > offset) {
moveDirections.Dequeue();
}
}
This would only work for the first body element, so you could add a script to each body element keeping track of its child body element. Position the child element with the same logic used above.
NOTE: I haven't tested this, I'm just trying to give a high-level overview of how to solve this problem.

Unity Jumping code for player not working

The jump button is not working in my unity, as my player is not jumping. I followed a tutorial but it does not seem to work. Must be something wrong with my code but I cannot seem to work it out as there are no errors.
I am not sure but, I created an image in unity and placed it in canvas and named it "Fixed Joybutton", with the script Joybutton.cs, but when I run it and try to click it, it wont make my player jump. I thought the problem was the "joybutton = FindObjectOfType();" and changed it to "joybutton = GetComponent();" but still doesnt work.
This is the code for the jump button itself, Joybutton.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
{
[HideInInspector]
public bool Pressed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnPointerDown(PointerEventData eventData)
{
Pressed = true;
}
public void OnPointerUp(PointerEventData eventData)
{
Pressed = false;
}
}
// and this is the code that is in my player, PlayerController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
protected Joystick joystick;
protected Joybutton joybutton;
protected bool jump;
public float speed;
public Text playerDisplay;
public Text scoreDisplay;
public bool isFlat = true;
private Rigidbody rb;
public static int count = 0;
private void Start()
{
joystick = FindObjectOfType<Joystick>();
joybutton = FindObjectOfType<Joybutton>();//this is to find the object, I changed it to "joybutton = GetComponent<Joybutton>();" but still doesnt work
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
rb.velocity = new Vector3(joystick.Horizontal * 5f, rb.velocity.y, joystick.Vertical * 5f); // joystick to move my player, its working
if (!jump && joybutton.Pressed)// this is for the jump, that is not working
{
jump = true;
rb.velocity += Vector3.up * 10f;
}
if (jump && !joybutton.Pressed)
{
jump = false;
}
}
public void OnTriggerEnter(Collider other)
{
GameObject gameControl = GameObject.Find("Timer");//name of my gameobject
Loading loading = gameControl.GetComponent<Loading>();
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
count = count + 1;
Awake();
}
else if (other.gameObject.CompareTag("Time Boost"))
{
other.gameObject.SetActive(false);
loading.sec += 10;
if (loading.sec > 60)
{
int sec1 = loading.sec - 60;
loading.sec = sec1;
loading.minutes ++;
}
Awake();
}
}
private void Awake()
{
if (DBManager.username == null)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
playerDisplay.text = "Player: " + DBManager.username;//display username
scoreDisplay.text = "Score: " + count.ToString();//display score
}
}
//Player is moving but cannot jump. Please show me the error in my code and solution. Thank you so much.
There's a lot to unpack here.
UI Events like OnPointerDown occur on the frame cycle. FixedUpdate happens on the fixed cycle. There is a good chance that you have a very high framerate, resulting in 5-6 frames per fixed cycle. Your joybutton will only be set to "pressed" for one frame, so there is a very high chance that the joybutton triggers OnPointerUp before the jump can occur.
The quickest solution to this problem would be to not "reset" the joybutton's pressed state using OnPointerUp, and instead reset it when the jump is processed in your PlayerController. That being said, can you help me understand why these 2 scripts are separated?
Rather than set the .Pressed state to false in the JoyButton script, reset it after you consume it in your PlayerController:
if (!jump && joybutton.Pressed)// this is for the jump, that is not working
{
jump = true;
joybutton.Pressed = false; //Add this line of code
rb.velocity += Vector3.up * 10f;
}
How do yo do for avoiding the player to jump twice in the air?
private void FixedUpdate()
{
rb.velocity = new Vector3(
joystick.Horizontal * 5f, rb.velocity.y,
joystick.Vertical * 5f);
if (!jump && joybutton.Pressed)
{
jump = true;
rb.velocity += Vector3.up * 10f;
}
if (jump && !joybutton.Pressed)
{
jump = false;
}
}

Mouse clicks aren't recognized when I build Unity game

EDIT : Apparently when I select Windowed, the buttons work. Why is this? Why doesn't it work without that box selected?
I created a game in Unity and everything works fine in Unity itself. When I build and run the game, my buttons no longer recognize my mouse clicks. Why is this?
This is a basic pong game. I don't know why it would work in Unity and not outside of Unity if it was the code but here is the code.
Code :
paddle script:
using UnityEngine;
using System.Collections;
public class paddle : MonoBehaviour {
public float paddleSpeed = 1;
public Vector3 playerPos = new Vector3(0,0,0);
// Update is called once per frame
void Update () {
float yPos = gameObject.transform.position.y + (Input.GetAxis ("Vertical") * paddleSpeed);
playerPos = new Vector3 (-20,Mathf.Clamp(yPos, -13F,13F),0);
gameObject.transform.position = playerPos;
}
}
ball script:
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float ballVelocity = 1500;
private Rigidbody rb;
private bool isPlay; //false by default
int randInt; //random ball directon when game begins
// Use this for initialization
void Awake () {
rb = gameObject.GetComponent<Rigidbody> ();
randInt = Random.Range (1,3);
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0) == true && isPlay == false){
transform.parent = null;
isPlay = true;
rb.isKinematic = false;
if(randInt == 1){
rb.AddForce(new Vector3(ballVelocity,ballVelocity,0));
}
if(randInt == 2){
rb.AddForce(new Vector3(-ballVelocity,-ballVelocity,0));
}
}
}
}
enemy script:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public float speed = 8;
private Vector3 targetPos;
private Vector3 playerPos;
private GameObject ballObj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
ballObj = GameObject.FindGameObjectWithTag ("ball");
if (ballObj != null) {
targetPos = Vector3.Lerp (gameObject.transform.position, ballObj.transform.position, Time.deltaTime * speed);
playerPos = new Vector3 (-20, Mathf.Clamp (targetPos.y, -13F, 13F), 0);
gameObject.transform.position = new Vector3 (20, playerPos.y, 0);
}
}
}
score script:
using UnityEngine;
using System.Collections;
public class Score : MonoBehaviour {
public TextMesh currScore;
public GameObject ballPref;
public Transform paddleObj;
GameObject ball;
private int score;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
ball = GameObject.FindGameObjectWithTag("ball");
currScore.text = "" + score;
}
void OnTriggerEnter(Collider other) {
if(other.tag == "ball"){
score += 1;
Destroy(ball);
(Instantiate(ballPref, new Vector3(paddleObj.transform.position.x + 1, paddleObj.transform.position.y,0), Quaternion.identity) as GameObject).transform.parent = paddleObj;
}
}
}
title screen script:
#pragma strict
function Start () {
}
function Update () {
}
function StartGame () {
Application.LoadLevel("Main");
}
function ExitGame () {
Application.Quit();
}
From what I am understanding, you want Unity to recognize your mouse button event even when the mouse pointer is not inside the game Window.
There could be 2 ways to achieve this:
1. The easy way, make your game full screen.
2. If you want your game in a window box, you must check "Run In Background" option in Player settings -> Resolution. And then, learn how to hook mouse event: http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C
Please note that the hooking mouse event tutorial only works on Windows, not Mac nor Linux. I do not know how to do it with Mac or Linux.

OnGUI is called just in first component

I'm creating a game to learn about Unity watching a tutorial (this one) and my Player has two components: PlayerHealth and PlayerAttack. The both are working fine as well but the problem is when I tried to do something in a OnGUI of second component (PlayerAttack), the OnGUI in PlayerAttack is never called.
Is because PlayerAttack is added below PlayerHealth? Follow below the codes e some prints.
PlayerHealth.cs
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLenght;
// Use this for initialization
void Start () {
healthBarLenght = Screen.width / 3;
}
// Update is called once per frame
void Update () {
AddjustCurrentHealth(0);
}
void OnGUI(){
GUI.Box(new Rect(10, 10, healthBarLenght, 20), curHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj){
curHealth += adj;
curHealth = Mathf.Min(Mathf.Max(curHealth, 0), maxHealth);
maxHealth = Mathf.Max(maxHealth, 1);
healthBarLenght = ((float) Screen.width / 3) * (curHealth / (float) maxHealth);
}
}
PlayerAttack.cs
using UnityEngine;
using System.Collections;
public class PlayerAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float coolDown;
// Use this for initialization
void Start () {
attackTimer = 0;
coolDown = 2;
}
// Update is called once per frame
void Update () {
if(attackTimer > 0){
attackTimer -= Time.deltaTime;
} else {
attackTimer = 0;
}
if(Input.GetKeyUp(KeyCode.F) && attackTimer == 0){
attackTimer = coolDown;
Attack();
}
}
void onGUI(){
float loadPct = coolDown - attackTimer;
GUI.Box(new Rect(10, 30, loadPct, 10), loadPct + "%");
}
private void Attack(){
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
Debug.Log(direction);
if(distance <= 2.5 && direction > 0.9)
{
EnemyHealth eh = (EnemyHealth) target.GetComponent("EnemyHealth");
eh.AddjustCurrentHealth(-1);
}
}
}
Your OnGUI method on PlayerAttack class is typed "onGUI", not "OnGUI" (capital O). Remember C# is case-sensitive.

Categories

Resources