Unity - GameObject won't destroyed when hit a prefab - c#

In the game you controll a ball (Sphere) and two types of boxes falling down: deathCube and goldCube. When the Sphere hit the DeathCube, then the Sphere is destroyt, but it not get destroyed and I don't know why. The cubes are prefabs and they have a tag(DeathCube, GoldCube).
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "DeathCube")
{
Destroy (gameObject);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "GoldCube")
{
gold++;
}
}
If the Sphere hit the goldCube you get points, but this doesn't work too.

Try merging the two OnTriggerEnter's into one.
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "DeathCube")
{
Destroy (gameObject);
}
if (other.gameObject.tag == "GoldCube")
{
gold++;
}
}
I believe that the second one is overriding the first, never allowing the Destroy() to be called. I would've assumed the compiler would throw an error with this, but you don't seem to have indicated that.

If you don't have a rigidbody attached to at least one of the objects in the collision (ball or cube), then the trigger event won't be initiated.
From the documentation:
Notes: Trigger events are only sent if one of the colliders also has a rigidbody attached
Source: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter.html

Related

Trigger is not detecting Collisions with other colliders

I have a GameObject that I only want to collide with certain objects, I added a trigger and checked for OnTriggerEnter. However, the rocket doesn't detect collisions with the Turret Object.
Thanks in advance for anyone who helps!
Rocket Script:
void OnTriggerEnter2D(Collider2D other)
{
UnityEngine.Debug.Log("Collision Detected with" + other);
if (other.gameObject.tag == "Player")
{
PlayerController.health -= 75.0f;
Die();
}
if (other.gameObject.tag == "Boss 1")
{
Boss1Controller.health -= 100;
Die();
}
if (other.gameObject.tag == "Turret")
{
Destroy(other);
}
}
Never mind, I figured it out, it turns out that triggers don't work with Edge Colliders2D so I just used a Polygon Collider2D instead. The shape is isn't as perfect as before but it's good enough.
Rookie Mistake, sorry.

Unity gameObject without a script is reaching a collision method

So I am taking a class in basic game development and am currently working on a game with Unity. My game worked perfectly up until now when I updated my unity version. In order for the player to actually take damage I have a method that can only be reached if explicitly called by a script. Somehow the ground, that has no script attached, damages my player.
I have posted the code below.
This one is part of the player script
3 references
public void Hurt(int dmg, string yep)
{
HP -= dmg;
Debug.Log($"took {dmg} damage from{yep}. You now have {HP} HP left");
if (HP <= 0)
{
SceneManagement.Death();
}
}
This one is part of the script attatched to my flame object
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag != "FlameTurret" && collision.gameObject.tag != "flame")
{
player.GetComponent<PlayerController>().Hurt(damage, collision.gameObject.tag);
Destroy(this.gameObject);
}
}
This one is attatched to a projectile fired by the enemy
if (collision.gameObject.CompareTag("Player"))
{
if (!called)
{
collision.gameObject.GetComponent<PlayerController>().Hurt(damage, collision.gameObject.tag);
called = true;
}
}
This one is attatched to an enemy
if (collision.gameObject.CompareTag("Player"))
{
if (!called)
{
collision.gameObject.GetComponent<PlayerController>().Hurt(damage, collision.gameObject.tag);
called = true;
}
Destroy(this.gameObject);
}
Console output
Nothing with the tag "Ground" has a script and nothing else than the methods i've posted are supposed to reference my Hurt() method but the ground still damages my player. Any help would be greatly appreciated!
Your problem seems to be that this function here
private void OnCollisionEnter2D(Collision2D collision)
Will be run whenever any collider (game object with a collider component attached - the game object does not need to have any scripts attached to it) intersects with your player
This code here
if (collision.gameObject.tag != "FlameTurret" && collision.gameObject.tag != "flame")
Will pass so long as the object that collides does not have the tag of "FlameTurret" or "flame", which I assume your ground does not.
It seems to me a little odd that everything in your game will damage your player except for flames... is this an error?
Either way a simple fix would be to tag your ground with something like environment and then add under your OnCollisionEnter2D() have a check along the lines of
if (collision.gameObject.tag == "environment"){
return; // do nothing
}

Destroy object if NOT in collision?

Would like to know if it is possible to destroy an object if not in collision with anything?
When I start the game I generate a grid randomly, on each GridSquare I've made a collider2D. In the editor, I add some objects on this grid manually, with a collider2D too and a rigidbody2D to detect the collision.
I know how to destroy the object if in a collision, what I want is "when the game start, if this object is not in collision with anything, then destroy it"
I've tried to tell unity "if in collision with grid square then destroy object (just for testing), else destroy object"
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.name == "GridSquare")
{
Destroy(gameObject);
}
else {
Destroy(gameObject);
}
}
So actually it destroys well the object when it is on a GridSquare, and it should destroy object if it is not in collision with GridSquare too but apparently not...
private var collisionCount = 0;
void OnCollisionEnter () {
collisionCount++
}
void OnCollisionExit () {
collisionCount--;
}
void checkForCollision(){
if(0 == collisionCount) Destroy(gameObject);
}
If the gameObject is not colliding, OnTriggerEnter2D method wont be activated for that specific gameObject. Bear in mind that method only triggers on collision event.
For that case you might have in your gameObjects a boolean _isColliding which you can change with the OnTriggerEnter2D method to check the ones that are colliding, setting that to true.
bool _isColliding = false;
void OnTriggerEnter2D(Collider2D collision)
{
_isColliding = true;
}
Then you loop through all of the gameObjects and destroy only the ones that have the _isColliding == false.
Hope that helps!

destroy a specific gameobject after an amount of time in unity

I kinda stuck with my script right now. When a gameObject, with my script attached to it, has a trigger event with a specific gameObject, I want to destroy the specific gameObject after an amount of time.
So i came to this:
void OnTriggerEnter ( Collider other) {
if (other.gameObject.tag == "leaf1"){
StartCoroutine (LeafDestruction ());
}
}
IEnumerator LeafDestruction(){
yield return new WaitForSeconds (5);
Destroy (gameObject);
}
I know it's a noob mistake but i think i miss something, because when i run this script, it destroys the gameObject with the script attached to it, and not the specific gameObject(with tags).
How can i fix that?
A simpler solution is to use the optional 2nd parameter of the Destroy method:
The object obj is destroyed immediately after the current Update loop, or t seconds from now if a time is specified.
Given the official parameters:
Parameters
obj
The object to destroy.
t
The optional amount of time to delay before destroying the object.
You can adjust your if statement to:
if (other.gameObject.tag == "leaf1")
Destroy(other.gameObject, 5.0f);
Basically you need to tell your coroutine that it should destroy the other.gameObject and not the gameObject that is running this script.
So what you could do is add a parameter to your coroutine, passing in the gameObject that it should really be destroyed:
void OnTriggerEnter ( Collider other) {
if (other.gameObject.tag == "leaf1")
{
IEnumerator coroutine = LeafDestruction(other.gameObject);
StartCoroutine (coroutine);
}
}
IEnumerator LeafDestruction(GameObject toDestroy){
yield return new WaitForSeconds (5);
Destroy (toDestroy);
}
You destroyed the object instead of the leaf. The gameObject is an alias of this.gameObject, which is the game object this script component is attached to. Note MonoBehaviour inherits from Behaviour and Behaviour inherits from Component.
GameObject leafObject;
void OnTriggerEnter ( Collider other) {
if (other.gameObject.tag == "leaf1"){
leafObject = other.gameObject;
StartCoroutine (LeafDestruction ());
}
}
IEnumerator LeafDestruction(){
yield return new WaitForSeconds (5);
Destroy (leafObject);
}

unity OnTriggerStay2D() for two triggers

I am using unity 5 c# and I have a gameobject with 2 trigger colliders one of them is in a different location.
I need to be able to use OnTriggerStay2D and OnTriggerEnter2D for them but I need to find what trigger is being entered. Right now if I enter the 1st(polygon) trigger the OnTriggerEnter activates for the 2nd(box).
How can I Tell the two colliders apart???
public void OnTriggerEnter2D(Collider2D other) //2nd collider trigger
{
if (other.tag == "Player") {
Found = true; //if the player is in shooting range
Idle = false;
}
}
public void OnTriggerStay2D(Collider2D other) //1st collider trigger
{
if (Found != true) {
if (other.tag == "Player") {
Shield = true;
Idle = false;
}
}
}
public void OnTriggerExit2D(Collider2D other) //2nd collider trigger
{
if (other.tag == "Player") {
Found = false;
Shield = false;
Shooting = false;
Idle = true;
}
}
I have tried making the 1st trigger public void OnTriggerStay2D(PolygonCollider2D other) but it says "This message parameter has to be of type: Collider2D
The message will be ignored."
What I am trying to do is have a polygon trigger in front of the gameobject and a different box trigger closer to the gameobject so when you go near the gameobject you enter the 1st trigger and it puts its shield up but when you get close to it (within shooting range of it) it will put its shield down and start shooting you.
Well collider2d detects all types of 2d colliders. It doesn't matter if it's polygon or just a box. As the documentation suggestions it doesn't need to be public or private. It only takes a collider2d as it's argument however.
For debugging purposes why not use print?
Print("you've entered the trigger function");
Also I wouldn't use 2 different trigger colliders on the same GameObject. Why not just make 2 separate gameobjects so you can have more thorough detection. Each GameObject with its own trigger collider can have different tags.
If you have to use 2 trigger colliders on one object. Which isn't the best idea. You could use shapeCount to determine which one it's hitting. Although like I said I would warrant against doing 2 trigger colliders on the same object when whatever you're trying to do can be easier on two separate objects.
However links aren't usually prohibited I think. I would watch and study these videos. They're very useful for explaining the engine and they really aren't even that long.
https://unity3d.com/learn/tutorials/modules/beginner/2d
They even have a video explaining 2d colliders.
This is my fix. In one of my games I have a boulder, I have a trigger which will delete a block below it so it falls, I then have another trigger which tells the boulder to start moving left or right I then also have another trigger which will delete the boulder once the boulder comes in contact.
So what you can do is create 2 new game objects, create a new CS file and name them appropriately, then with those two new classes allow them to take in the gameobject you are referring to in your question.
Then when they are triggered you can use code from their class.
So your first class would become something like this
public void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player") {
Enemy.Found = true; //if the player is in shooting range
Enemy.Idle = false;
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player") {
Enemy.Exit2DTrigger();
}
}
Then the other class would be something like this
public void OnTriggerStay2D(Collider2D other)
{
if (Enemy.Found != true) {
if (other.tag == "Player") {
Enemy.Shield = true;
IEnemy.dle = false;
}
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player") {
Enemy.Exit2DTrigger();
}
}
Then in your Enemy class you would have
public void Exit2DTrigger()
{
Found = false;
Shield = false;
Shooting = false;
Idle = true;
}
P.S. also don't you need to use other.gameObject.tag == "Player" ?

Categories

Resources