error in unity time.deltatime running still after asked to stop - c#

The problem is with the time delta.time function. It runs even after time Left variable crosses the value 0. I am an absolute newbie to coding so please help me.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float speed = 1;
private int count;
//Text UI variables
public Text countText;
public Text winText;
public Text Timer;
private bool outOfTime = false;
public float totalTime = 15.00f;
private float timeLeft;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetTextUpdate();
winText.text = "";
timeLeft = totalTime;
// time left was declared as total time
}
void Update()
{
}
void FixedUpdate()
{
if (timeLeft < 0)
{
winText.text = "Oops, you lost";
outOfTime = true;
}
else
{
timeLeft = timeLeft - Time.deltaTime;
}
// the time left still continues to reduce even after reaching 0.
Timer.text = timeLeft.ToString();
float movementHorizontal = Input.GetAxis("Horizontal");
float movementVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(movementHorizontal, 0.0f, movementVertical);
rb.AddForce(movement * speed);
timeLeft -= Time.deltaTime;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
count = count + 1;
SetTextUpdate();
}
}
void SetTextUpdate()
{
countText.text = "Count: " + count.ToString();
if (count == 10 && outOfTime == false)
{
winText.text = ("You win");
}
}
}
I am a complete newbie to coding so I hope to get help soon. It's just a simple 'Roll a Ball' game that I tried to modify with my given experience.

In FixedUpdate you are continuing to decrement the time and updating the display, even after time has run out. Try this:
void FixedUpdate()
{
if (timeLeft < 0)
{
Timer.text = timeLeft.ToString();
winText.text = "Oops, you lost";
outOfTime = true;
}
else
{
timeLeft = timeLeft - Time.deltaTime;
Timer.text = timeLeft.ToString();
}
// assume you want physics to continue after time is up
float movementHorizontal = Input.GetAxis("Horizontal");
float movementVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(movementHorizontal, 0.0f, movementVertical);
rb.AddForce(movement * speed);
// don't need this line timeLeft -= Time.deltaTime;
}

Related

Unity3D go down on slopes with a animated character

I'm developping a 3D game Unity with a squirrel as the player.
I'm struggling with a problem of slopes. I know, there are a bunch of tutorial to go down a slope whithout 'floating in the air while walking' but I didn't find a fine solution. I think it's because of the horizontal animations of the squirrel (maybe). I have tried with addForce, with a modified speed, with gravity... (maybe I implemented it wrong). I know I can check if I'm in the air or not with CharacterController.isGrounded but I can't force the squirrel to stick on the slope while running or walking. I'm sorry by advance if my question is too vague or simple.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class Squirrel : MonoBehaviour {
Animator squirrel;
public float gravity = 1.0f;
private Vector3 moveDirection = Vector3.zero;
float axisH, axisV;
public static int munitions = 0;
Rigidbody rb;
[SerializeField]
float walkSpeed = 2f, runSpeed = 8f, rotSpeed = 100f, jumpForce = 350;
private bool isJumpKeyDown = false;
[SerializeField] bool isJumping = false;
Animator characterAnimator;
int JumpCount = 0;
public int MaxJumps = 1; //Maximum amount of jumps (i.e. 2 for double jumps)
[SerializeField] GameObject nb_munitions;
CharacterController characterController;
// Use this for initialization
void Start () {
munitions = 0;
squirrel = GetComponent<Animator>();
rb = GetComponentInChildren<Rigidbody>();
characterAnimator = GetComponent<Animator>();
JumpCount = MaxJumps;
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
GetInput();
nb_munitions.GetComponent<Text>().text = "Glands : " + munitions; //Affichage du score
Move();
}
private void FixedUpdate()
{
if (isJumpKeyDown)
{
squirrel.SetTrigger("jump");
JumpCount -= 1;
isJumpKeyDown = false;
}
}
public void GetInput()
{
axisV = Input.GetAxis("Vertical");
axisH = Input.GetAxis("Horizontal");
}
private void Move()
{
if (characterController.isGrounded)
{
//On the ground
}
else
{
//on the air
}
if (axisV > 0)
{
if (Input.GetKeyDown(KeyCode.LeftControl))
{
transform.position += Vector3.forward * walkSpeed * Time.deltaTime;
squirrel.SetBool("walk", true);
}
else
{
transform.position += Vector3.forward * runSpeed * Time.deltaTime;
squirrel.SetFloat("run", axisV);
squirrel.SetBool("walk", false);
}
}
else
{
squirrel.SetFloat("run", 0);
}
if (axisH != 0 && axisV == 0)
{
squirrel.SetFloat("h", axisH);
}
else
{
squirrel.SetFloat("h", 0);
}
if (axisH != 0)
{
transform.Rotate(Vector3.up * rotSpeed * Time.deltaTime * axisH);
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (JumpCount > 0)
{
isJumpKeyDown = true;
}
}
//Call munitions
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (Squirrel.munitions > 0)
{
SpawnerScript.Instance.NewSpawnRequest();
munitions--;
}
}
}
}
You can try to get the angle of the slope and make it the pitch for the mesh of the squirrel.
I finally found the problem. My C# script "overwrited" the CharacterController and did not allow the squirrel to go down the slopes. Make sure you follow a move script that "respects" the CharacterController (if you pick one or you'll be fighting windmills).

transform.position not working in Unity 3d

I'm really new to Unity 3d and I'm trying to make a respawn with my character. It seems that the answer is really easy but I cannot see why my code is not working. If this is a duplicate, let me know.
public Vector3 PointSpawn;
void Start()
{
PointSpawn = gameObject.transform.position;
}
void Update()
{
if (gameObject.transform.position.y < 10)
{
gameObject.transform.position = PointSpawn; // This doesn't work
// gameObject.transform.LookAt(PointSpawn); ---> This DOES work ok
}
}
Parallel Script
public float HorizontalMove;
public float VerticalMove;
private Vector3 playerInput;
public CharacterController player;
public float MoveSpeed;
private Vector3 movePlayer;
public float gravity = 9.8f;
public float fallVelocity;
public float JumpForce;
public bool DoubleJump = false;
public Camera mainCamera;
private Vector3 camForward;
private Vector3 camRight;
void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
HorizontalMove = Input.GetAxis("Horizontal");
VerticalMove = Input.GetAxis("Vertical");
playerInput = new Vector3(HorizontalMove, 0, VerticalMove);
playerInput = Vector3.ClampMagnitude(playerInput, 1);
CamDirection();
movePlayer = playerInput.x * camRight + playerInput.z * camForward;
movePlayer = movePlayer * MoveSpeed;
player.transform.LookAt(player.transform.position + movePlayer);
setGravity();
PlayerSkills();
player.Move(movePlayer * Time.deltaTime );
}
void CamDirection()
{
camForward = mainCamera.transform.forward;
camRight = mainCamera.transform.right;
camForward.y = 0;
camRight.y = 0;
camForward = camForward.normalized;
camRight = camRight.normalized;
}
void PlayerSkills()
{
if (player.isGrounded && Input.GetButtonDown("Jump"))
{
fallVelocity = JumpForce;
movePlayer.y = fallVelocity;
DoubleJump = true;
}
else if (player.isGrounded == false && Input.GetButtonDown("Jump") && DoubleJump == true)
{
fallVelocity = JumpForce *2;
movePlayer.y = fallVelocity;
DoubleJump = false;
}
}
void setGravity()
{
if (player.isGrounded)
{
fallVelocity = -gravity * Time.deltaTime;
movePlayer.y = fallVelocity;
}
else
{
fallVelocity -= gravity * Time.deltaTime;
movePlayer.y = fallVelocity;
}
}
Thanks in advance!
Just so the answer to the question is not in the comments:
The original problem is that the assignment gameObject.transform.position = PointSpawn appeared to do nothing. As the line is written properly, the position of this gameObject, must have been getting overwritten elsewhere.
With the addition of OP's movement script, the position of the player was getting overwritten in the movement's Update function. As the other assignment was being done in Update, the call order was not guaranteed to work as intended. The fix is either to assure that the movement Update is run not the frame of the new position assignment or to move the conditional and the assignment to a function that always runs after Update regardless of script execution order, LateUpdate.

C# code works in one script, but not the other

I am currently learning C# as I'm studying a Games Design Course at University. I am currently implementing a system where: when the time reaches 0, the game pauses and ends. This works :).
However, at first I tried implementing the code into another script - but doesn't work on that script. This has puzzled me. Here is the code (that works):
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health : MonoBehaviour
{
private Text TimeText;
public float HealthTimer;
public bool TimeIsRunning;
public GameObject CanvasEnd;
void Start()
{
TimeText = GameObject.Find("Timer").GetComponent<Text>();
TimeIsRunning = true;
CanvasEnd.SetActive(false);
}
void Update()
{
TimeText.text = HealthTimer.ToString("0");
if (TimeIsRunning == true)
{
if (HealthTimer > 0)
{
HealthTimer -= 1 * Time.deltaTime;
}
else
{
Time.timeScale = 0;
CanvasEnd.SetActive(true);
}
if(HealthTimer == 0)
{
TimeIsRunning = false;
HealthTimer = 0;
}
}
This script is directly attached to the timer. But I don't understand why it doesn't work when I implement it into another script (that already controls other game aspects). There were no errors, and everything was declared properly.
The exact same code was put into this script (in void update) and didn't work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public GameObject Player;
public GameObject PlayerTracker;
public GameObject BlueBottle;
public GameObject GreenBottle;
public GameObject RedBottle;
public GameObject ChestCanvas;
public float Score;
public float ChestScoreK = 0;
private Text HT;
private Text HC;
private Text Port;
private Text TimeText;
float speed = 4;
float rotSpeed = 80;
float rot = 0f;
float gravity = 8;
// Variables counting Blue, Red and Green bottles
public int BBCounter = 0;
public int RBCounter = 0;
public int GBCounter = 0;
public int CCounter = 0;
Vector3 moveDir = Vector3.zero;
CharacterController controller;
Animator anim;
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
ChestCanvas.SetActive(false);
TimeText = GameObject.Find("Timer").GetComponent<Text>();
}
void Update()
{
//Script was implemented here
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.W))
{
anim.SetInteger("condition", 1);
moveDir = new Vector3(0, 0, 1);
moveDir *= speed;
moveDir = transform.TransformDirection (moveDir);
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetInteger("condition", 0);
moveDir = new Vector3(0, 0, 0);
}
}
rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime;
transform.eulerAngles = new Vector3(0, rot, 0);
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime);
}
private void FixedUpdate()
{
PlayerTracker.transform.position = Player.transform.position;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "BlueBottle")
{
Debug.Log("BLUE");
BBCounter = BBCounter + 1;
GameObject MasterScriptBlue = GameObject.Find("GameMaster");
MasterScriptBlue.GetComponent<GameMasterScript>();
MasterScriptBlue.GetComponent<GameMasterScript>().BlueBottleCounter = BBCounter;
}
if (other.gameObject.tag == "RedBottle")
{
Debug.Log("RED");
RBCounter = RBCounter + 1;
GameObject MasterScriptRed = GameObject.Find("GameMaster");
MasterScriptRed.GetComponent<GameMasterScript>();
MasterScriptRed.GetComponent<GameMasterScript>().RedBottleCounter = RBCounter;
}
if (other.gameObject.tag == "GreenBottle")
{
Debug.Log("GREEN");
GBCounter = GBCounter + 1;
GameObject MasterScriptGreen = GameObject.Find("GameMaster");
MasterScriptGreen.GetComponent<GameMasterScript>();
MasterScriptGreen.GetComponent<GameMasterScript>().GreenBottleCounter = GBCounter;
}
if(other.gameObject.tag == "CityCollider")
{
GameObject HuntingCity = GameObject.Find("HC");
Destroy(HuntingCity);
ScoringSystem.theScore += 100;
Destroy(other.gameObject);
Debug.Log("Destroyed");
}
if(other.gameObject.tag == "TownCollider")
{
GameObject HuntingTown = GameObject.Find("HT");
Destroy(HuntingTown);
ScoringSystem.theScore += 100;
Destroy(other.gameObject);
Debug.Log("Destroyed");
Debug.Log("Destroyed");
}
if(other.gameObject.tag == "PortCollider")
{
GameObject Port = GameObject.Find("Port");
Destroy(Port);
ScoringSystem.theScore += 100;
Destroy(other.gameObject);
Debug.Log("Destroyed");
}
if(other.gameObject.tag == "Chest")
{
Time.timeScale = 0;
ChestCanvas.SetActive(true);
ChestScoreK += 1;
GameObject MasterScriptChest = GameObject.Find("GameMaster");
MasterScriptChest.GetComponent<GameMasterScript>().ChestScore += ChestScoreK;
Destroy(other.gameObject);
GameObject HealthScript = GameObject.Find("Timer");
HealthScript.GetComponent<Health>().TimeIsRunning = false;
}
}
}
What can I try next?
It's hard to understand the problem from your question, but if you are looking for potential problems in your script then it looks like you are comparing a float to zero here:
if(HealthTimer == 0)
{
TimeIsRunning = false;
HealthTimer = 0;
}
So it is possible that HealthTimer is never exactly zero.
You probbaly want if (HealthTimer <= 0f) instead, or to move that block into the else block of your preceding if statement.
Other differences with the second script are:
the second script is not setting TimeIsRunning = true; in the Start() method,
other methods set Time.timeScale = 0; in the second script (not sure what impact this has, but may be relevant).
Do you have the same 'using' tags at the top of your scripts? The 'text' class only exists in UnityEngine.UI, and not UnityEngine.

Character doesn't jump sometimes - Unity

I am new to Unity and I am using the following CharacterController for my character. Everything is working well, except that sometimes the character jumps and sometimes it doesn't when I hit the spacebar. I used Debog.Log using Raycast to check if my character is grounded, and the result was True. So what is preventing my character from jumping whenever I hit the key?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class RPGMovement : MonoBehaviour
{
public float ForwardSpeed = 8f;
public float BackwardSpeed = 4f;
public float StrafeSpeed = 5f;
public float RotateSpeed = 110f;
CharacterController m_CharacterController;
Vector3 m_LastPosition;
Animator m_Animator;
PhotonView m_PhotonView;
PhotonTransformView m_TransformView;
float m_AnimatorSpeed;
Vector3 m_CurrentMovement;
float m_CurrentTurnSpeed;
Vector3 playerVelocity;
private bool groundedPlayer;
private float jumpHeight = 0.9f;
private float gravityValue = -20.81f;
void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Animator = GetComponent<Animator>();
m_PhotonView = GetComponent<PhotonView>();
m_TransformView = GetComponent<PhotonTransformView>();
}
void Update()
{
if (m_PhotonView.isMine == true)
{
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
}
UpdateAnimation();
}
void UpdateAnimation()
{
Vector3 movementVector = transform.position - m_LastPosition;
float speed = Vector3.Dot(movementVector.normalized, transform.forward);
float direction = Vector3.Dot(movementVector.normalized, transform.right);
if (Mathf.Abs(speed) < 0.2f)
{
speed = 0f;
}
if (speed > 0.6f)
{
speed = 1f;
direction = 0f;
}
if (speed >= 0f)
{
if (Mathf.Abs(direction) > 0.7f)
{
speed = 1f;
}
}
m_AnimatorSpeed = Mathf.MoveTowards(m_AnimatorSpeed, speed, Time.deltaTime * 5f);
m_Animator.SetFloat("Speed", m_AnimatorSpeed);
m_Animator.SetFloat("Direction", direction);
m_LastPosition = transform.position;
}
void ResetSpeedValues()
{
m_CurrentMovement = Vector3.zero;
m_CurrentTurnSpeed = 0;
}
void ApplySynchronizedValues()
{
m_TransformView.SetSynchronizedValues(m_CurrentMovement, m_CurrentTurnSpeed);
}
void MoveCharacterController()
{
m_CharacterController.Move(m_CurrentMovement * Time.deltaTime);
}
void UpdateForwardMovement()
{
if (Input.GetKey(KeyCode.W) || Input.GetAxisRaw("Vertical") > 0.1f)
{
m_CurrentMovement = transform.forward * ForwardSpeed;
}
}
void UpdateBackwardMovement()
{
if (Input.GetKey(KeyCode.S) || Input.GetAxisRaw("Vertical") < -0.1f)
{
m_CurrentMovement = -transform.forward * BackwardSpeed;
}
}
void UpdateStrafeMovement()
{
if (Input.GetKey(KeyCode.Q) == true)
{
m_CurrentMovement = -transform.right * StrafeSpeed;
}
if (Input.GetKey(KeyCode.E) == true)
{
m_CurrentMovement = transform.right * StrafeSpeed;
}
}
void UpdateRotateMovement()
{
if (Input.GetKey(KeyCode.A) || Input.GetAxisRaw("Horizontal") < -0.1f)
{
m_CurrentTurnSpeed = -RotateSpeed;
transform.Rotate(0.0f, -RotateSpeed * Time.deltaTime, 0.0f);
}
if (Input.GetKey(KeyCode.D) || Input.GetAxisRaw("Horizontal") > 0.1f)
{
m_CurrentTurnSpeed = RotateSpeed;
transform.Rotate(0.0f, RotateSpeed * Time.deltaTime, 0.0f);
}
}
void UpdateJump()
{
groundedPlayer = m_CharacterController.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
m_Animator.SetTrigger("Jump");
print("Jumping Now");
}
playerVelocity.y += gravityValue * Time.deltaTime;
m_CharacterController.Move(playerVelocity * Time.deltaTime);
}
}
Best guess is that "m_PhotonView.isMine" is not returning true on the frames where you're missing input. It only checks jump input for that frame, so if the last frame you pressed it but jumping wasn't checked then that input is lost forever. First test this. Change the update code to this:
void Update()
{
if (Input.GetButtonDown("Jump")) { Debug.Log("Jump was pressed at {Time.time}"); }
if (m_PhotonView.isMine == true)
{
if (Input.GetButtonDown("Jump")) { Debug.Log("Attempting Jump at {Time.time}"); }
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
}
UpdateAnimation();
}
Then play the game and jump a bunch. The first debug log line should happen every time you click the spacebar no matter what. The second debug line would only happen if physics are calculated that frame. Both have times attached. Keep jumping until the jump doesn't work. If that jump only produces the first debug log and not the second, then I am correct and that is your issue.
If so, then it's an easy fix. Add a new bool variable called "jumpInput". Whenever you check if jump was pressed, instead check if "jumpInput" is true. Then, change update to this:
void Update()
{
if (Input.GetButtonDown("Jump")) { jumpInput = true; }
if (m_PhotonView.isMine == true)
{
ResetSpeedValues();
UpdateRotateMovement();
UpdateForwardMovement();
UpdateBackwardMovement();
UpdateStrafeMovement();
MoveCharacterController();
UpdateJump();
ApplySynchronizedValues();
jumpInput = false;
}
UpdateAnimation();
}
This way if you pressed jump, it's set to true... but it's only set to false after physics are done. So if you press jump on frame 20 and physics are somehow not calculated until frame 25, it'll still know that you pressed jump at some point and thus execute it. If you're using networking, you might want to also have another variable that's what frame jump was pressed. That way you can figure out how many frames it's been since input and compensate for missed time in the jump if necessary.

Unity C# Input.GetMouseDown(1) only happening once in update function

so i've been working on some code for a game in Unity and i am using the Input.GetMouseButtonDown(1) function. However, it only works the first time i press the left click in the game and no other times after that. The code for the player controller where it's used is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
public float speed;
public Transform enemy;
public Transform shot;
public GameObject shotObj;
public Text scoreT;
public Text timeT;
public Text roundT;
public float health;
public float damageTaken;
public Vector3 lookPoint;
public float shotSpeed;
private Camera mainCamera;
private int round = 1;
private int tempRound = 0;
private float time = 300;
private bool win = false;
private bool allowShoot;
private EnemyController enemyScript;
private ShotController shotScript;
private bool tempImune = false;
private int targetTime;
private int score = 0;
private int defeatedEnemy = 0;
private GameObject enemyObj;
//coroutine
IEnumerator Pause(float timE)
{
allowShoot = false;
//time since the object was created
float start = Time.realtimeSinceStartup;
//sets the game to slow down to 0 movement
Time.timeScale = 0.0f;
//loops until start up time is less than start time + pause time
while (Time.realtimeSinceStartup < start + timE)
{
//returns null from the subroutine and restarts the subroutine at this point after null (0) time has passed
yield return null;
}
//sets the gamne to be running at normal speed
Time.timeScale = 1.0f;
allowShoot = true;
if (timE == 5.0f)
{
roundT.gameObject.SetActive(false);
}
}
void Start () {
//center mouse
Cursor.lockState = CursorLockMode.Locked;
Cursor.lockState = CursorLockMode.None;
//set camera to be the camera in the scene (should only ever be one camera in the scene)
mainCamera = FindObjectOfType<Camera>();
//set default text values
scoreT.text = "Score: 000000";
timeT.text = "Time Left: 600";
roundT.text = "Round: " + round;
//pause game before first round begins
StartCoroutine(Pause(5.0f));
}
void Update () {
//looka at mouse script
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane ground = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (ground.Raycast(cameraRay, out rayLength))
{
lookPoint = cameraRay.GetPoint(rayLength);
transform.LookAt(new Vector3(lookPoint.x, transform.position.y, lookPoint.z));
}
//enemy spawner check and win criteria check
if (defeatedEnemy != 45)
{
if (round != tempRound)
{
spawnEnemy();
roundT.gameObject.SetActive(true);
if (round == 5)
{
roundT.text = "Round: " + round + "(Final Round)";
}
else
{
roundT.text = "Round: " + round;
}
StartCoroutine(Pause(5.0f));
}
}
else
{
win = true;
}
//timer and win check
if (health == 0f)
{
win = true;
}
if (!win)
{
time -= Time.deltaTime;
timeT.text = "Time Left: " + time;
}
else
{
if (health == 0f)
{
roundT.gameObject.SetActive(true);
int finalScore = Mathf.RoundToInt(score * ((time / 2) / 10));
roundT.text = "To Bad, You Loose! Score = " + finalScore;
Debug.Log(finalScore);
StartCoroutine(Pause(99999f));
}
else
{
roundT.gameObject.SetActive(true);
int finalScore = Mathf.RoundToInt(score * ((time / 2) / 10));
roundT.text = "Congratulations! Score = " + finalScore;
Debug.Log(finalScore);
}
}
//movement controlls
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(new Vector3(0.0f, 0.0f, speed * Time.deltaTime));
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(new Vector3(-speed * Time.deltaTime, 0.0f, 0.0f));
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(new Vector3(0.0f, 0.0f, -speed * Time.deltaTime));
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(new Vector3(speed * Time.deltaTime, 0.0f, 0.0f));
}
//shoot controll
if (allowShoot)
{
Debug.Log("shot allowed");
if (Input.GetMouseButtonDown(0))
{
//var spawnShot = Instantiate(shot, this.transform.position + new Vector3(0.0f, 0.0f, 0.5f), this.transform.rotation);
//shotScript = shotObj.GetComponent<ShotController>();
//if (shotScript.enemy)
//{
// Debug.Log("enemy found");
// enemyScript = shotScript.enemy.GetComponent<EnemyController>();
// if(enemyScript.health <= 0.0f)
// {
// score += 20;
// defeatedEnemy += 1;
// scoreT.text = "Score: " + score;
// Debug.Log("enemy killed : " + defeatedEnemy);
// }
//}
Debug.Log("mouseDown");
int layermask = 1 << 8;
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layermask))
{
enemyObj = hit.transform.gameObject;
enemyScript = enemyObj.GetComponent<EnemyController>();
Debug.Log("hit");
//hit.transform.SendMessage("HitByRay");
if (enemyScript.health == 0f)
{
Destroy(hit.transform.gameObject);
score += 20;
defeatedEnemy += 1;
scoreT.text = "Score: " + score;
Debug.Log("enemy killed : " + defeatedEnemy);
}
}
}
}
//enemy existance check
if (GameObject.Find("Enemy(Clone)") == null)
{
round = round + 1;
}
if (tempImune)
{
if (Mathf.RoundToInt(time) == targetTime)
{
tempImune = false;
}
}
}
void spawnEnemy()
{
tempRound = round;
for (int i = 1; i <= round * 3; i++)
{
var spawnEnemy = Instantiate(enemy, new Vector3(Random.Range(-14.5f, 14.5f), 0.25f, Random.Range(-6f, 6f)), Quaternion.identity);
}
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Enemy")
{
if (!tempImune)
{
health = health - damageTaken;
Debug.Log(health);
tempImune = true;
targetTime = Mathf.RoundToInt(time) - 1;
}
}
}
}
Any help with this would be greatly appreciated as it's for a school project. Thanks.
You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the mouse button and pressed it again. button values are 0 for the primary button (often the left button), 1 for secondary button, and 2 for the middle button
using UnityEngine;
using System.Collections;
public class ClassName : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
Debug.Log("Pressed primary button.");
if (Input.GetMouseButtonDown(1))
Debug.Log("Pressed secondary button.");
if (Input.GetMouseButtonDown(2))
Debug.Log("Pressed middle click.");
}
}

Categories