How to increase score when clone prefabs touch wall? - c#

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.

Related

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" );

Unity (C#) - How do I single out GameObject being detected by Raycast in a destroy / respawn system

I'm trying to make a Destroy gameobject, wait x seconds, respawn gameobject system. I have 2 scripts and I'm destorying then instantiating it again. I want to use multiples of the same prefab called "Breakable" but have only the one I'm aiming at being destroyed. Similar to games like Minecraft, aim and only the aimed at the block is destroyed.
BlockBreakItem script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockBreakItem : MonoBehaviour
{
RaycastHit hit;
int layerMask = 1;
public GameObject breakableObject;
public bool isObjectDestoryed = false;
public int score = 0;
// Update is called once per frame
void Update()
{
breakableDetection();
}
void breakableDetection()
{
Ray rayLocation = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(rayLocation, out hit, 1000, layerMask))
{
print("Detected");
if (Input.GetKey(KeyCode.Mouse0))
{
breakableObject = GameObject.Find("Breakable");
Destroy(breakableObject);
isObjectDestoryed = true;
score = score +1 ;
}
}
}
}
RespawnBrokenObject script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RespawnBrokenObject : MonoBehaviour
{
private BlockBreakItem BlockBreakItem;
public GameObject breakablePrefab;
// Start is called before the first frame update
void Start()
{
BlockBreakItem = GameObject.FindObjectOfType<BlockBreakItem>();
}
// Update is called once per frame
void Update()
{
if (BlockBreakItem.isObjectDestoryed == true)
{
Invoke("respawnObject", 5.0f);
BlockBreakItem.isObjectDestoryed = false;
}
}
void respawnObject()
{
GameObject tempObjName = Instantiate(breakablePrefab);
tempObjName.name = breakablePrefab.name;
BlockBreakItem.breakableObject = tempObjName;
}
}
I hope the code isn't too messy! Always worried it won't be understood xD
Fortunately it's easy and basic in Unity!
You don't do this:
breakableObject = GameObject.Find("Breakable");
The good news is the cast will tell you what object you hit! Great, eh?
It's basically:
hit.collider.gameObject
You can use hit.collider.gameObject.name in a Debug.Log for convenience.
It's that easy!
Note you then (if you need it) get your component on that object with something like .GetComponent<YourBreakishBlock>()... easy.
Note that you can CHECK if the object hit, is one of the "YourBreakishBlock" objects, by simply checking if that component is present.
Note simply google something like "unity physics raycast out hit, which object was hit ?" for endless examples,
https://forum.unity.com/threads/getting-object-hit-with-raycast.573982/
https://forum.unity.com/threads/changing-properties-of-object-hit-with-raycast.538819/
etc.
--
Make this simple class:
public class ExamplePutThisOnACube: MonoBehavior
{
public void SAYHELLO() { Debug.Log("hello!"); }
}
Now put that on SOME cubes but NOT on OTHER cubes.
In your ray code:
ExamplePutThisOnACube teste =
hit.collider.gameObject.GetComponent<ExamplePutThisOnACube>();
and then check this out:
if (teste != null) { teste.SAYHELLO(); }
Now run the app and try pointing at the various cubes!

How to make a kills counter in Unity2D with C#?

I want to make a kill counter but for some reason it's not working.
Here is what i did
I create a new empty GameObject Game Manager And add a new component Score, Here is the code:
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Text kills_UI;
private int Kills_Counts; //How many kills
public void Increase_score() //This will update the UI text to the current kills count
{
Kills_Counts++;
kills_UI.text = Kills_Counts.ToString();
}
}
After that i called this function in the enemy script BulletColision after he is killed :
using UnityEngine;
public class BulletColision : MonoBehaviour
{
Score kills_score;
void Start()
{
kills_score = GetComponent<Score>();
}
public void OnCollisionEnter2D(Collision2D others) //When a bullet collide with en enemy prefab
{
if (others.gameObject.CompareTag("Enemy"))
{
Destroy(gameObject); //Destroy the enemy
kills_score.Increase_score(); //Calling the function from 'GameManager'
Destroy(others.gameObject); //Destroy the bullet
}
}
}
The problem is with your kills_score reference, if you do:
kills_score = GetComponent<Score>();
You are searching for Score component on your BulletCollision, which I guess do not have Score component since it's a bullet.
Quick fix:
Attach to your GameManager a new TAG like "GameManager", then use
kills_score = GameObject.FindWithTag("GameManager").GetComponent<Score>();
instead of
kills_score = GetComponent<Score>();
To quickly validate this make your score variable public and see in your editor if the reference is correctly set.
Also and as a side note, try to maintain your variables with lowerCamelCame nomenclature, meaning that starts with lower case.

OnCollisionEnter not detecting

I am trying to make the game go to Dead scene when collided by does not work. And it even does not detect the collsion.
I've attached the script to empty game object that has box collider with is trigger ticked and the player does have a Rigidbody too.
I am not sure what is wrong, please help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Health : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnCollisionEnter(Collision collision)
{
Debug.Log("dead without if statement");
if (collision.gameObject.tag == "Player")
{
Debug.Log("Dead Mate");
SceneManager.LoadScene("DeadScreen");
}
}
}
"I've attached the script to empty game object that has box collider with is trigger ticked and the player does have a Rigidbody too."
If i understand you correct you enabled trigger on box collider if yes you must implement
void OnTriggerEnter(Collider col)
{
}
Not
public void OnCollisionEnter(Collision collision)
{
}

Unity Collision Detection - Adding GUI Score on Collision?

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.

Categories