unity text trigger not working as expected - c#

in my game im trying to make text appear on the ui when entering a specific room,but when i try to go into that room nothing happens
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Room_trigger : MonoBehaviour
{
public GameObject UiObject;
public GameObject cube;
void Start()
{
UiObject.SetActive(false);
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "player")
{
UiObject.SetActive(true);
}
}
void Update()
{
}
void OnTriggerExit(Collider other)
{
UiObject.SetActive(false);
Destroy(cube);
}
}
the player controller is based of of brakeys fps controller tutorial.

Three things you will need to check:
Does the player object (the one that the player capsule collider component is attached to) have the tag "player" assigned to it? Is it definitely "player" and not "Player" or "Player1". Note - the TAG of an object is not the same as the NAME of an object.
Is the "Is Trigger" on the capsule collider on the player object ticked/checked? If the player capsule collider is not a trigger then it won't cause OnTriggerEnter to be fired by your Room_trigger attached object. Also check the next point.
If you don't want your player capsule collider to be a trigger (which is highly likely), then make sure that the object your Room_trigger script is attached to has:
a collider that is set to Is Trigger
a Rigidbody component
A couple of other possibilities are that you haven't dragged GameObjects into the UiObject and/or cube fields in the Unity Editor UI but that should throw NullReference errors in the console when you run the game.
Whilst Vasmos is correct, you should compare strings using the Equals() method, that's not going to be the cause of your trouble in this specific case. Comparing strings using == as you've done here will work.

replace
if (other.tag == "player")
with
if (other.tag.Equals("player"))
always use .Equals for comparing strings, otherwise its just comparing if its the same variable

#HumanWrites i figured out what the problem was, the cube wasn't set as trigger, the i watched a different tutorial and he sayed "dont forget to set the collider as trigger" and that fixed it.

Related

How to check Collision detection for GameObjects of same prefab (Unity)

(For 2D Project)
I created a gameObject and made it a prefab.
Now when the game starts, the prefab is used to instantiate gameObjects and they all should check if they collide with one another.
I tried other unity's collision methods but it didn't work.
They either kept colliding with themselves (their own rigidbody) or it didn't work at all.
I'm new to unity and learning things. I searched every where but didn't get my question solved. I'll appreciate any help, Thank you!
Prefab is loaded and Instantiated as such..
GameObject tile = Instantiate(Resources.Load("Prefabs/Tile") as GameObject);
Its a basic gameObject having SpriteRenderer 2D.
I used Box Collider 2D and Rigidbody 2D components on that prefab -
Inspector
A simple script which has OnTriggerEnter2D(Collider2D other) function to check if it collides..
using UnityEngine;
public class TileCollider : MonoBehaviour {
public Rigidbody2D triggerBody;
void OnTriggerEnter2D(Collider2D other) {
if (triggerBody == null)
return;
if (other.attachedRigidbody == triggerBody) {
Debug.Log("Collision!");
}
}
}
I tried it without any if statements - It triggers collision for the Rigidbody2D of the gameObject (itself)
I passed the Prefab itself to check the collision for - Script in Inspector.
This is where were things get bad. It looks for the rigidbody of its own gameObject but I wanted it to search for other cloned gameObjects from same prefab.
The first thing to look at to solve the problem is to check if your prefabs have tags attached to them.
Assuming you have the TileCollider script attached on your prefab which it looks like it is in the inspector, you are checking if the other.attachedRigidbody is its own rigid body (triggerBody). And an object cannot collide with itself. You should probably check if its own rigid body is not the other.attachedRigidbody. If its not its own rigidbody then you have collision with another GameObject!
I hope I understood your question correctly, Thanks!
There looks to be quite a few errors with your code. First, you've got a triggerBody but it doesn't look like it's assigned. Hopefully you're assigning this manually as part of the prefab arrangement, but you could guarantee this by doing that hookup in Start and throwing an error if it fails to get the Rigidbody, like:
public Rigidbody2D triggerBody;
void Start()
{
if(triggerBody == null) // Would happen if it's not set in the prefab
{
triggerBody = gameObject.GetComponent<RigidBody2D>();
}
if(triggerBody == null) // Would happen if there is no Rigidbody2D attached at all!
{
Debug.LogErrorFormat("Failed to find a Rigidbody2D to use with {0}!", gameObject.name);
}
}
Another issue is that you're asking for collisions, but your code is looking for triggers. Here's a link to an article, but the short version is that if you're checking OnTriggerEnter then at least one of the colliders involved needs to have the IsTrigger option ticked:
Another issue is that you're bailing on the operation if the triggerBody is null. As I mentioned at the start, you're not explicitly setting the triggerBody in your code, so if it's also not set in the prefab then you'd abort here even if the collider options were set correctly.
Finally, and probably most importantly, is this snippet doesn't make sense:
if (other.attachedRigidbody == triggerBody) {
Debug.Log("Collision!");
}
What you're saying here is that you want there to be a collision if the other rigidbody is the same as the local rigidbody. This would ensure the behavior you described in your post,
They either kept colliding with themselves (their own rigidbody) or it didn't work at all.
You're only calling it a collision if they're colliding with themselves! The way to check if it's NOT self-colliding is to make sure the other.attachedRigidbody is NOT equal to the local triggerBody!
What you would want instead would be:
if (other.attachedRigidbody != triggerBody) {
Debug.Log("Collision!");
}

Enemy won't get destroyed when I hit it

private void OnTriggerEnter(Collider other)
{
if(other.tag == "Melee")
{
Destroy(gameObject);
}
}
The code shown above is the code in my enemy script that lets it die when the player's knife hits it. The knife is tagged as Melee. When the knife hits the enemy, it doesn't get destroyed.
Things you can check.
Is your collider 3D?
At least one of the two colliding objects must have a Rigidbody.
Also make sure the typo in "Melee".
One more thing, Make sure your collider is in Trigger Mode.

My projectiles wont collide with my enemies in a 2D side scrolling Unity project?

As the title suggests, I've literally just started learning Unity recently and I'm practising by making a side scrolling shooter. I've been following a Udemy course about it and (to my knowledge) I've been following the tutor's instructions to the letter, but at the point where he tests his and it works fine, by projectiles go straight through my enemies.
I'm a bit stumped at this point and so I thought I'd post here to see what you guys thought. I bet it's something really simple I've not done.
Please see my projectile code below:
using UnityEngine; using System.Collections;
public class DestroyEnemyAndProjectile : MonoBehaviour {
public GameObject WhiteExplosion;
public GameObject OrangeExplosion;
void Start()
{
}
void Update()
{
}
void OnCollisionEnter2D (Collision2D tempCollision)
{
if (tempCollision.gameObject.tag == "Collision")
{
spawnParticles(tempCollision.transform.position);
Destroy(tempCollision.gameObject);
}
}
void spawnParticles(Vector2 tempPosition)
{
Instantiate(WhiteExplosion, tempPosition, Quaternion.identity);
Instantiate(OrangeExplosion, tempPosition, Quaternion.identity);
}
}
Thanks for your help!
I did post a question to them which got a response, they suggested that perhaps the projectile is going too fast and check there was a Rigidbody 2D attached - both of which were already collect
make sure that the object you're colliding with has the tag "Collision", with the same capitalisation.
If it's not, you can do this by:
1. Selecting the GameObject to be collided with
2. In the top-right, select the Tag property
3. Add tag, click the plus and type in "Collision"
4. Select the GameObject again, and select the "Collision" tag from the Tag property dropdown
Otherwise, if that's not the issue. Make sure the projectile has a type of Collider2D component, and that the projectile, or the object being collided with, has a Rigidbody2D.
First I would like to know what the behaviour of this script curently is. Is the collision method being called, and the projectile goes through the enemy anyway? Or the collision method is not being called at all?
That being said, these are things that you should check in order for collision to work:
Make sure that the projectile and the enemy have Collider2D components attached to them.
Make sure that the projectile and/or the enemy (at least one of them must) have a Rigidbody2D attached to it.
Make sure that the layer of the projectiles and the layer of the enemies are set to collide in the collision matrix (You can find the collision matrix in Edit->ProjectSettings->Physics)
Make sure that the enemy GameObject has its tag set to "Collision".
P.S: Welcome to Unity where issues like this are, in fact, usually caused by something super simple that you probably missed.

Unity Spawning way to much objects on collision

im working on an demolition/simulator type game. im working on the basics but my scripts doesnt seem to be working. the idea of the script is, that if the objects encounters an "hard" enough force, it will get replaced by a destroyed version of that object. it works in on small structures. but when the structures get bigger instead of spawning 1 destroyed object, it seems to spawn waaaayy more. and thus the game starts to lag. I think it is becouse some objects hit other objects. when i destroy them by clicking it doesn't happen, only when they hit each other
hope anyone can help.
here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destructible : MonoBehaviour {
public GameObject debrisPrefab;
void OnCollisionEnter( Collision collision )
{
if (collision.relativeVelocity.magnitude > 3f)
{
Destroy(gameObject);
Destroy();
}
}
void OnMouseDown()
{
Destroy(gameObject);
Destroy();
}
void Destroy()
{
if (debrisPrefab)
{
Instantiate(debrisPrefab, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
Does you debris prefab contain other destructible object? Maybe the newly instantiated debris are all destroyed if the spawn and have a collision right away.
Another thing to check is how many elements can trigger the collision. If you have many colliders on your object, onCollisionEnter will be called several times. Also, are you sure you added your script only once to the object?
Finally, if this doesn't help, try using debug lines:
Debug.Log(name + " collision enter");
to print lines in the console with the name of the colliding object, to try to identify which object causes too many collisions

OnCollisionEnter2D fails to send information

I am testing OnCollisonEnter2D and it doesn't seem to want to work for me.
I have box collider 2d and rigidbody2d's on both of my game objects and again, it fails to send a message to the console.
using UnityEngine;
using System.Collections;
public class CollisionAndResetSystem : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Cube")
print ("hit");
}
}
I took this strait from the Scripting API and it doesn't want to work.
There is no problem in the script. Problem must be in your "boxcollider2d" component. Please check the size of "boxcollider2d", change it to something like 100 in both x and y and in both the gameobjects also. Please check in the scene view if you can see the "boxcollider2d" gizmo. You have to make "boxcollider2d" as big as your gameobjects, then only OnCollisionEnter2D will work.
If you dont need your objects to be affected by physics
then set isKinematic = false and Gravity Scale = 0 and remember to attach your OnCollisionEnter2D script to your gameObject
A Couple of things:
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Cube")
print ("hit");
}
Make sure you are comparing with a correct tag (keep the case sensitivity in mind).
Make sure the gameObject that is being compared has this tag linked. May be you defined the tag but there is no gameObject with this tag.
Check the size of your collider component, it should be enough big to receive touch event.
Hope it helps!
Most important is that check on which gameobject your script is attached,Cross check that your script are attached to your gameobject that you are trying get collision with. And Use Debug.log() too in place of Print(),Hope this help.

Categories