Unity Collision Detection - Adding GUI Score on Collision? - c#

I am making a pinball game in Unity, and I have an issue. When the pinball collides with a cylinder to add points to the score, it does not work. I have tagged the cylinders in Unity and have attached this script to the pinball. It doesn't even show up in the debug log.
Thanks for any advice.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Score : MonoBehaviour {
public int scorePoint = 10;
public int MaxScore;
public Text ScoreText;
// Use this for initialization
void Start () {
ScoreText = GetComponent<Text>();
ScoreText.text = "Score: " + scorePoint;
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Cylinder")
{
Debug.Log("Collision detected");
scorePoint+=10;
}
}
// Update is called once per frame
void Update()
{
}
}

Make sure you have a box collider on each object. OnTriggerEnter is only called when two box collider hit each other. This is the most likely culprit of why its not working but without more information I can't guarantee it.

Related

How to increase score when clone prefabs touch wall?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CountScoreAtWall : MonoBehaviour
{
//Varriables
public GameObject[] prefabs;
public Text animalPassedText;
public int animalPassed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
animalPassedText.text = animalPassed.ToString();
}
void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == tag)
{
animalPassed = animalPassed + 1;
Debug.Log("Animal Passed showed");
}
}
I want to let my clone Prefabs from Instantiate() touch the wall and then the score will Increase by 1 to animalPassedText but I don't know how to do that.
So please help me. ToT
Possible solutions:
1- Either the wall or your prefab should have a rigidbody to make OnTriggerEnter work. So check if one of your game objects has a rigidbody and they both have colliders.
2- Maybe your "tag" variable is not matching with collision.gameObject.tag, so if block is not triggered. Print collision.gameObject.tag and tag to see if they are matching.

When my game in unity starts, my character collides with objects it isn't touching

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pickup : MonoBehaviour
{
public GameObject _Pickaxe;
// Start is called before the first frame update
void Start()
{
_Pickaxe = GameObject.Find("Pickaxe");
}
// Update is called once per frame
void Update()
{
}
void DestroyGameObject()
{
Destroy(gameObject);
}
private void OnTriggerEnter(Collider collision)
{
Debug.Log("Collided with +" + collision.gameObject.name);
if(collision.gameObject.name == "Pickaxe" );
{
Debug.Log("Touched pick");
}
}
}
In my script it logs whatever the character touches. In my scene i have a object placed about 10m away from where the player capsule spawns, somehow it collides with it before you can even move.
Your code have an error. It logs "Touched pick" for every collision. To fix it, your should remove the semicolon in this line if(collision.gameObject.name == "Pickaxe" );

How can I make it so that the player loses health when an enemy collides with a different object?

Here an image of what my game looks like so far so that you can get a better idea but I need it so that when one of the outer capsules touches the red box the player (middle capsule) loses health.
I have tried creating a new script which checks for collisions but I couldn't get it to work and am unsure where to go from here. Below is my code for how the health bar works and pressing the space bar reduces health for demonstration purposes.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public float MaxHealth;
public Slider _slide;
private float currentHealth;
void Start()
{
currentHealth = MaxHealth;
_slide.maxValue = MaxHealth;
_slide.value = MaxHealth;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
TakeDamage(25f);
if(currentHealth <=0)
{
//move to game over
}
}
void TakeDamage(float Damage)
{
currentHealth = currentHealth - Damage;
_slide.value = currentHealth;
}
}
At one point I tried using
void Update()
{
(collision.collider.name == "Barrier");
TakeDamage(25f);
if(currentHealth <=0)
{
//move to game over
}
}
but realised this is completely wrong, as well as trying to add a box collider to the red "barrier" to aid this but it didn't fix anything.
Update 2:
Also tried changing it so that the enemies move towards the barrier and not the player and added the code:
private void OnTriggerEnter(Collider other) {
TakeDamage(25f);
if(currentHealth <=0)
{
//move to game over
}
}
which doesn't present any errors but rather just doesn't do anything. The enemy capsules just go through it and to the centre, with no health being lost.
You need to check for collisions using OnCollisionEnter3D and then use the TakeDamage function inside of it. Here is an example:
public class PlayerHealth: MonoBehaviour
{
void OnCollisionEnter3D(Collision3D col) //Check for collision
{
TakeDamage(25f);
}
}
Note that for this function to work, both objects need a 3d collider and a rigid body. If you don't want your character to fall, just set gravity to 0.

Text does not update in Unity C#

I'm designing a game for my project and somehow the score(text) does not update after an action. It stuck at 0.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class uiManager : MonoBehaviour {
public Text scoreText;
bool gameOver;
int score;
// Use this for initialization
void Start () {
gameOver = false;
score = 0;
InvokeRepeating ("scoreUpdate", 1.0f, 0.5f);
}
// Update is called once per frame
void Update ()
{
scoreText.text = "Point: " + score;
}
void scoreUpdate()
{
if (gameOver == false)
{
score += 1;
}
}
public void gameOVER()
{
gameOver = true;
}
public void Play()
{
Application.LoadLevel ("MuachiJump");
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "branch")
{
score += 1;
Destroy(col.gameObject);
}
}
I just want to make sure is there any mistake in this code? All of them seem to be correct.
The code by itself seems fine. Make sure that uiManager is attached to an object in your scene that is active. In the Update method, if you add, for example, Debug.Log(score), it should print to the log every frame. If this isn't happening, you need to attach the script to an object in your scene as well as make sure that the Text object has a valid reference.
Do you have an active object with the script attached on your scene?
In my case the size of the textbox was the issue, just enlarge it and your score will be visible.

Trigger not working properly with GetComponent. What is wrong?

Here is the player health script... It set's the players health from within Unity, and pushes it onto the GUI.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public Text hpText; //HP Value Text Element.
public int PlayerHP; // Make it a property so you can alter its value in the editor
void Start()
{
SetHPText ();
}
void Update ()
{
SetHPText ();
}
void SetHPText ()
{
hpText.text = "Health: " + PlayerHP.ToString();
}
}
Then this one takes the grabs the players current health (and keeps it updated). If the players health is 0 (or lower) it loads a new scene. The problem is the tag tag check for the player, and apply damage aren't working.
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class DamageAuroa : MonoBehaviour {
public int PHP; //PHP = Player Health from PlayerHealth.cs script.
public int Damage; //Amount of damage.
public string Level;
void Update()
{
PHP = GameObject.Find("Player").GetComponent<PlayerHealth>().PlayerHP;
}
void OnTriggerEnter(Collider coll)
{
if (coll.gameObject.tag == "Player")
PHP = PHP - Damage;
if (coll.gameObject.tag == "Ball")
{
gameObject.SetActive(false);
SceneManager.LoadScene(Level);
}
if (PHP <= 0)
SceneManager.LoadScene(Level);
}
}
The weirdest part ALL OF THIS was working prior to me updating Unity (I know newbie mistake). Anyone see what's the matter? Before anyone asks yes the triggers, and tags are set up properly. Also I realize I have to pass the updated HP value to the player health script for it to update on the GUI. Just trying to get these triggers working.
Following code doesn't work because you are creating new variable PHP that equals to player HP (but doesn't reference to it, because int is a value type, not a reference type) and when you change PHP it changes only this variable, not PlayerHP from PlayerHealth script.
void Update()
{
PHP = GameObject.Find("Player").GetComponent<PlayerHealth>().PlayerHP;
}
void OnTriggerEnter(Collider coll)
{
if (coll.gameObject.tag == "Player")
PHP = PHP - Damage;
....
}
If you want to change PlayerHealth you should change it directly from PlayerHealth script instance.
if (coll.gameObject.tag == "Player")
GameObject.Find("Player").GetComponent<PlayerHealth>().PlayerHP= PHP - Damage;
Or you can create an reference type variable references to PlayerHealth script.
public class DamageAuroa : MonoBehaviour {
PlayerHealth player;
void Start ()
{
player = GameObject.Find("Player").GetComponent<PlayerHealth>();
}
...
And then use this object to set players hp.
if (coll.gameObject.tag == "Player")
player.PlayerHP = player.PlayerHP- Damage;
Aye well I am not sure if this will work because i am not as advanced my self, but try using coll.tag, because the collier class has a tag variable it self.

Categories