I have a GUI on my scene saying "Capsules Collected: 0/10" and a capsule object which has Collider that whenever the player enters the capsule , the capsule will be destroyed and the Capsules Collected will be increased by 1.
The Destroy Works well, the GUI isnt displaying. What is wrong with my code?
Here's my Code, I assigned this C# script on the Player itself:
using UnityEngine;
using System.Collections;
public class CapsuleGET : MonoBehaviour {
int capscore=0;
void Start(){
}
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
capscore =capscore+1;
}
void Update(){
GUILayout.Label("Capsules Collected: "+capscore+"/10");
}
}
Like this .. very easy
using Unity.UI;
public class CapsuleGET
public Text displayScore; // DRAG to connect in Editor
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
capscore =capscore+1;
displayScore.text = capscore.ToString();
1 - click to add canvas (don't forget to select 'scale with screen size')
2 - click to add Text, position as you want.
3 - in your script, "public Text score"
4 - drag from the "Text" to that variable
explanation with diagrams
Related
I am writing a script that shows a collision between one object and an obstacle. The code runs but does not output within the console. Is there something that I am doing wrong?
using UnityEngine;
public class collision : MonoBehaviour{
void OnConllisionEnter (Collision collisionInfo)
{
if(collisionInfo.collider.tag == "Obstacle")
{
Debug.Log("We Hit an obstacle!");
}
}
}
I added a tag to the object as I will be adding more obstacles to simplify the process. I checked for semicolons and any other errors that would stand out to me. I am not sure what I am supposed to change or if I am missing something.
You actually have a typo in the methods name
// Here
// |
// v
void OnConllisionEnter (Collision collisionInfo)
The code should be
using UnityEngine;
public class collision : MonoBehaviour{
void OnCollisionEnter (Collision collisionInfo)
{
if(collisionInfo.collider.tag == "Obstacle")
{
Debug.Log("We Hit an obstacle!");
}
}
}
When using OnConllisionEnter, check your collider component to make sure the [Is Trigger] flag isn't checked
Collider Component, Is Trigger Flag
Also, remember that both objects have to have a collider component attached to them and only one of them will need a rigid body component attached to it (both of which have to match the correct world space, i.e. 2D/3D RigidBody and Collider.
More about Collisions:
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
I'm making a game, and I'm having trouble making the score appear on the game.
So far, this is all I have:
public class keepingScore : MonoBehaviour {
public static double homeScore;
// Use this for initialization
void Start ()
{
double homeScore = 5.0;
print(homeScore);
}
}
So my code is printing 5 to the console, and when I've tried other methods, it says it wont work because homeScore is not a string.
Any help guys?
Thanks!
Please try use GUI:
https://docs.unity3d.com/ScriptReference/GUI.html
or you can try Canvas GUI that must better:
https://docs.unity3d.com/Manual/UICanvas.html
So first of all what you need if you want to have score in your GUI is to have a Text component in your scene.
Once you have your Text component in your scene you need to create a script that will handle the score and add it to the Text component you have created. This is an example of a Score manager script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class keepingScore : MonoBehaviour {
public static double homeScore;
Text text;
void Awake () {
text = GetComponent<Text>();
homeScore = 0.0;
}
// Update is called once per frame
void Update () {
text.text = "Score: " + homeScore;
}
}
Now you can attach this script to the Text component you have created earlier. What this script does is first retreive the Text component that it is attached too and initialize a public static double homeScore that you can access and modify from any script by just doing keepingScore.homeScore. Finally the Update function will run every frame to update the Text component you have.
Now that you have a Text component in your scene with this script attached to it, you can start modifying the value of your score. From wherever you want. An example would be let's say when your player picks up a coin you want to give him 1 point, so if the player collides with the coin you add 1 to the homeScore
void OnCollisionEnter(Collision collision) {
if (collision.CompareTag("Coin"))
keepingScore.homeScore++;
}
This would for example add 1 to the score when the player collides with the coin.
You can do keepingScore.homeScore += pointAmount wherever you want to add points to the player and it will automatically update the GUI Text.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour {
public int Player_Health = 100;
public GameObject Player;
public Rigidbody Bullet;
public Transform Guun;
public bool Player_Dead = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
Rigidbody rocketInstance;
rocketInstance = Instantiate(Bullet, Guun.position, Guun.rotation) as Rigidbody;
rocketInstance.AddForce(Guun.forward * 5000);
}
if(Player_Health == 0)
{
Player_Dead = true;
}
if(Player_Dead == true)
{
Destroy(Player);
}
}
private void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "Player")
{
Player_Health = Player_Health - 20;
Debug.Log(Player_Health);
}
}
}
1.So when i instantiate by pressing space it first instantiates 1 then 2 then 4 then 8 and so on - why doesnt it just instantiate 1 each press.
I am trying to make a gun here and obviously need it to only fire one bullet at a time because at the moment it fires multiple. As i have already explained first it fires one bullet then next time i fire it doubles it and so on.
1.So when i instantiate by pressing space it first instantiates 1 then 2 then 4 then 8 and so on - why doesnt it just instantiate 1 each
press.
If the behavior is that each prefab duplicates each time the key is pressed, it simply means that the script is also attached to the prefab or multiple GameObjects. I see similar problems each time.
Please remove the script from the prefabs if it is attached to any prefab. Remove it from every GameObject in the scene then attach it to one GameObject only.
Select the script, go to Assets --> Find References in Scene. It will show you every GameObject that has this script attached to it. Remove it from all of them except for one.
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);
}
}
}
How can I add the game object from above (Roed Knap, Hand etc.) into the script given below (at the picture)?
This is an example project. I can't figure out to reference GameObject's and Colliders into a Script.
What I want to do is very simple.
Make a GameObject with a Collider, and trigger something when collision happens.
So What I have is basically a GameObject Cube that has a Collider sphere added and for this isTrigger is selected. I want this trigger when entering, modify the text. Can you help me with initializing, referencing and other stuffs necessary, see below code. This is the code I work with.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
GameObject Cube;
GUIText Text;
Collider collision;
// Use this for initialization
void Start () {
collision = Cube.GetComponent<Collider> ();
Text = GetComponent ("GuiText") as GUIText;
}
// Update is called once per frame
void Update () {
}
void onTriggerEnter(){
Text.text = "Won"
}
}
Unity uses C# syntax for all of MonoBehaviour and engine namings. That is, a method starts with cap letter:
void OnTriggerEnter(Collider col){}