I'm trying to make a countdown attached to a sprite. The countdown will count down from 10 to zero, and won't be attached to the Canvas, so it won't be static on the screen. All of the tutorials for something like this have been for UI and don't allow 3D text. Anyone have any ideas on how to do this?
There are two ways to do this:
Use UI elements on a separate canvas set to World Space
Use the TextMesh element to put a 3D mesh of text in the world
I don't really know the pros and cons of each approach so go with whichever is easier for you to implement and keep the other in mind if you run into problems.
If you're looking for a detailed tutorial, anything explaining how to do popup damage numbers will be the same method, just with a different script telling it what text to display. There are a few good tutorials on the top of the YouTube results.
As for the countdown script, it's fairly simple.
//put this script on a GameObject prefab with a TextMesh component, or a canvas element
public class Countdown : MonoBehaviour
{
public TextMesh textComponent; //set this in inspector
public float time; //This can be set in inspector for this prefab
float timeLeft;
public void OnEnable()
{
textComponent = GetComponent<TextMesh>(); //in case you forget to set the inspector
timeLeft = time;
}
private void Update()
{
timeLeft -= Time.deltaTime; //subtract how much time passed last frame
textComponent.text = Mathf.CeilToInt(timeLeft).ToString(); //only show full seconds
if(timeLeft < 0) { gameObject.SetActive(false); } //disable this entire gameobject
}
}
Related
I've been trying to fix this one bug in my code for over 7 hours now, upon being teleported, the movement controls cease to function, the mouse works fine, you can look around, but you can't move around.
I wanted to set up some simple code that would teleport the player to a "checkpoint" upon achieving a negative or null y level. I was doing this for a parkour based game, if the player fell off the platform they would have to start over, but after teleporting, it becomes impossible to move as I'm sure I have already said. My code is pretty simple:
public class Main : MonoBehaviour
{
float Fall;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 Checkpoint = new Vector3 (0,3,0);
GameObject Player = GameObject.FindGameObjectWithTag("Player");
Fall = GameObject.FindGameObjectWithTag("Player").transform.position.y;
if (Fall<-4)
{
Player.transform.position = Checkpoint;
}
}
}
You would think that this would just simply change the coordinates of the player, but I think this might be screwing with the FPSController script.
I am using Unity3d, with Standard Assets imported, All of the code is in C#.
Instead of checking the Y value of your character, I would instead place a death collider under the map. Make this a trigger and if the player touches this trigger, then teleport them back. Nothing with your code should screw with the FPS controller so it might be something else. I would also highly recommend not using a FindGameObjectWithTag in the Update() method as it is extremely expensive to use this every frame, especially twice. If you would rather keep the Update() Y component of the position check, please rewrite the code to something like this:
public class Main : MonoBehaviour
{
// assign this object of your player in the inspector - it stores the reference to reuse
// instead of grabbing it every frame
[SerializeField] private Transform playerTransform = null;
// make this a variable as it is not changing - might as well make this const too
private Vector3 checkpoint = new Vector3(0, 3, 0);
// constant value of what to check for in the Y
private const int FALL_Y_MARKER = -4;
// Update is called once per frame
void Update()
{
if (playerTransform.position.y < FALL_Y_MARKER)
{
playerTransform.position = checkpoint;
}
}
}
With your current code, there should be nothing breaking your input/movement, but with that said, we can not see your input/movement code. All the above snippet does is check if the Y component of the player objects position is below a certain value, and if it is, it sets the position to a new vector. Can you post a bit more movement code or somewhere else it can go wrong that you think is the issue?
I am trying to create a script for my enemy turret, but it is not going well. I have a couple animations of the turret being activated and deactivated. What I need is that based on the distance from the player, it plays either animation. So once it moves inside the detection radius it plays the activation animation and once it is outside it plays the deactivation animation. Most of the other ways I try require me to create an Animation Controller, which I have little experience in using. I want a simple way to play one animation once it is inside and play a different one when it is outside. I think there was a way to store the animation clip in the script, and then play it. I have attached my current script, so you know what I mean.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTurret : MonoBehaviour
{
public GameObject Player;
public float DistanceToPlayer;
public float DetectionRadius = 75;
// Start is called before the first frame update
void Start()
{
Player = GameObject.FindGameObjectWithTag("PlayerTank");
}
// Update is called once per frame
void Update()
{
DistanceToPlayer = Vector3.Distance(transform.position, Player.transform.position);
if (DistanceToPlayer<=DetectionRadius)
{
Debug.Log("Within Radius");
}
if (DistanceToPlayer >= DetectionRadius)
{
Debug.Log("Outside Radius");
}
}
}
Calculating and checking the distance of the player for every update() is not ideal. It will work, but it will do more work than it needs to when the player isn't even near it. Its not efficient.
What you may want to do if your player is a Rigidbody, is add a SphereCollider to the turret, set isTrigger=true, set the radius to be your detection radius, and handle the OnTriggerEnter() and OnTriggerExit() events to play or stop animations.
You can also add two public Animiation objects to the script, drag and drop your animations in the editor, then you can use animation.Play() and .Stop() etc. to control the animations.
Something similar to this. Not tested fully, but you can get the idea.
public float detectionRadius = 75;
public Animation activateAnimation;
public Animation deactivateAnimation;
void Start()
{
SphereCollider detectionSphere = gameObject.AddComponent<SphereCollider>();
detectionSphere.isTrigger = true;
detectionSphere.radius = detectionRadius;
detectionSphere.center = Vector3.zero;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PlayerTank")
{
activateAnimation.Play();
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "PlayerTank")
{
deactivateAnimation.Play();
}
}
Your animations must not loop otherwise you will have to add more logic to check if animation.isPlaying and do your own animation.Stop() etc.
I am very new at C# (around 1 week in), so I have been following a lot of tutorials. I am at the moment trying to edit a piece of code (unity tutorial) to only have the enemy follow the player when in a certain range of the player (10 foot), but unfortunately without changing the code completely, I cannot find a solution. At the moment the enemy will only follow the player when the player is alive (which i also want).
I've tried googling what I want, but I don't want to change the code from what is it too much. I am very new at c# and and currently learning bit by bit, other methods I have found require me changing the code a lot. As far as I understand, the main focus of the code below is for the enemy to be completely controlled by the Nav Mesh Agent, is it possible for me to keep the same technique?
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour
{
Transform player;
PlayerHealth playerHealth;
EnemyHealth enemyHealth;
UnityEngine.AI.NavMeshAgent nav;
void Awake()
{
// references
player = GameObject.FindGameObjectWithTag("Player").transform;
playerHealth = player.GetComponent<PlayerHealth>();
enemyHealth = GetComponent<EnemyHealth>();
nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void Update()
{
if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
nav.SetDestination(player.position);
transform.LookAt(player);
}
else
{
nav.enabled = false;
}
}
}
If possible, I would like to add 2 if functions. 1 being the check if the player is alive, and the other to check if the player is within distance. I don't know much about raycast at the moment, so will this be the next step for me to learn to get this to work how i want?
Thankyou for your time.
Dean.
You can calculate distance by doing:
float distance = Vector3.Distance(player.transform.position,transform.position);
You can do a check if it's no larger than some amount with:
bool playerIsCloseEnough = distance <= amount;
And you can check if the player is alive with:
bool playerIsAlive = playerHealth.currentHealth > 0;
Then, you can do things if they're both true with:
if (playerIsAlive && playerIsCloseEnough)
{
// ...
}
And as you mentioned in the comment, you'll need to set nav.enabled=true; in void Awake or void Start to make sure the nav mesh is turned on :)
This is semi complicated of a question but I'll do my best to explain it:
I am making this mobile game in which you have to shoot four cubes. I'm trying to make it so when the cubes are shot by a bullet, they're destroyed and a UI text says 1/4, to 4/4 whenever a cube is shot. But it's being really weird and only counts to 1/4 even when all four cubes are shot and destroyed. I put these two scripts on the bullets (I made two separate scripts to see if that would do anything, it didn't)
And to give a better idea of what I'm talking about, here's a screenshot of the game itself.
I've been using Unity for about 6 days, so I apologize for anything I say that's noob-ish.
EDIT
So I combined the two scripts onto an empty gameobject and here's the new script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameManagerScript : MonoBehaviour {
public GameObject cubes;
public Text countText;
public int cubeCount;
public Transform target;
// Use this for initialization
void Start () {
}
void OnTriggerEnter(Collider other)
{
cubes = other.gameObject;
}
// Update is called once per frame
void Update () {
cubes.transform.position = Vector3.MoveTowards(transform.position, target.position, 1f * Time.deltaTime);
if (cubes.gameObject.tag == "BULLET")
{
cubeCount = cubeCount + 1;
countText.text = cubeCount + "/4";
cubes.SetActive(false);
}
}
}
ANOTHER EDIT
I tried everything, so is there a way to detect when all the children in a parent on the Hierarchy are destroyed? Instead of counting up? This can give a better idea:
So I want to be able to detect when Cube, Cube1, Cube2, and Cube3 have all been destroyed.
The answer is pretty simple: Since every individual bullet has that script, each bullet has its own score.
For something like a score you want a single spot to store it, e.g. a script on an empty gameobject that serves as game controller. Just access that in the collision and increase the score (maybe have a look on singletons here).
You can combine those two scripts and actually it might be better to not have this on the bullet, but on the target because there are probably less of them which will save you some performance. (And it does more sense from a logical point of view.)
Edit:
I assume you create the bullets using Instantiate with a prefab. A prefab (= blueprint) is not actually in the game (only objects that are in the scene/hierarchy are in the game). Every use of Instantiate will create a new instance of that prefab with it's own version of components. A singleton is a thing that can only exist once, but also and that is why I mention it here, you can access it without something like Find. It is some sort of static. And an empty gameobject is just an object without visuals. You can easily create one in unity (rightclick > create empty). They are typically used as container and scriptholders.
Edit:
What you want is:
An empty gameobject with a script which holds the score.
A script that detects the collision using OnTriggerEnter and this script will either be on the bullets or on the targets.
Now, this is just a very quick example and can be optimized, but I hope this will give you an idea.
The script for the score, to be placed on an empty gameobject:
public class ScoreManager : MonoBehaviour
{
public Text scoreText; // the text object that displays the score, populate e.g. via inspector
private int score;
public void IncrementScore()
{
score++;
scoreText.text = score.ToString();
}
}
The collision script as bullet version:
public class Bullet : MonoBehaviour
{
private ScoreManager scoreManager;
private void Start()
{
scoreManager = GameObject.FindWithTag("GameManager").GetComponent<ScoreManager>(); // give the score manager empty gameobject that tag
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Target") == true)
{
// update score
scoreManager.IncrementScore();
// handle target, in this example it's just destroyed
Destroy(other.gameObject);
}
}
}
I am developing a game using unity3D and I need help making a progress time bar such that on collecting particular items time is added and thus the game continues.
Create a UI Image that is of type Filled. Use horizontal or vertical fill depending on your progress bar. Then from inside a script you can manipulate the value of the image. I will give you a very simple c# example. For the rest you can just use google and read the unity scripting API.
public class Example: MonoBehaviour {
public Image progress;
// Update is called once per frame
void Update ()
{
progress.fillAmount -= Time.deltaTime;
}
}
U could use a slider en slider.setvalue.
Example:
//to use this add first a slider to your canvas in the editor.
public GameObject sliderObject; //attachs this to the slider gameobject in the editor or use Gameobject.Find
Slider slider = sliderObject.GetComponent<Slider>();
float time;
float maxtime; //insert your maxium time
void start(){
slider.maxValue = maxtime;
}
void update()
{
time += Time.deltaTime;
if (time < maxtime)
{
slider.value = time;
}
else
{
Destroy(sliderObject);
//time is over, add here what you want to happen next
}
}