Unity 2D Trigger should only get triggered by one Player Prefab - c#

I have a 2D game with one player as a prefab. And I have an apple with a 2D Trigger on it. But I only want that the trigger only gets triggered by the Player Prefab and not by the moving platforms.
But if i do this:
if (other.CompareTag ("Player")) {
or this:
if (other.gameObject.tag == "Player") {
My Trigger doesn't recognize the Player.
What should I do?
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NeuerTrigger : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Geht");
}
}

You are probably not understanding how trigger is working.
Make sure that
1 On your apple there is a rigidbody and a collider with isTrigger to true
2 On your player there is a collider and a rigidbody
3 ON your player you have the tag "Player" in the inspector
If this is all like this then if you put this on the apple script:
void OnTriggerEnter2D(Collider2D other)
{
if(other.compareTag("Player")
// player touches apple
}

Related

Instantiated gameObject's self-written component is not working

I'm trying to implement chest mechanic in my game. When a user touches to chest, chest disappears and heart shows up. When player touches the instantiated heart, it must disappear and add 1 to life value, but the script is not working.
Chest.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chest : MonoBehaviour
{
public GameObject heart;
public GameObject _heart; //Instantiated heart.
void OnTriggerEnter2D(Collider2D col){
if (col.gameObject.tag == "Player"){
Vector3 insPos = transform.position;
_heart = Instantiate(heart,new Vector3(insPos.x,insPos.y+0.5f,insPos.z),Quaternion.identity);
_heart.AddComponent<Heart>();
_heart.GetComponent<Heart>().ls = GameObject.FindGameObjectWithTag("Player").GetComponent<LifeSystem>();
Destroy(gameObject);
}
}
}
Heart.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Heart : MonoBehaviour
{
public LifeSystem ls;
void OnTriggerEnter2D(Collider2D col){
if (col.gameObject.tag == "Player"){
SoundManager.PlaySound("CollectCoinSound");
ls.lifes += 1;
Destroy(gameObject);
}
}
}
I check the components of the instantiated heart when player touches the chest and I can see that life system reference is added and so heart script is.
Thanks for your time.
You need to meet these conditions in order for OnTriggerEnter2D to be called on the spawned Hearth:
At least one between Player and Hearth need to have a Rigidbody2D component
Both Player and Hearth need to have a collider with IsTrigger = true
Player and Hearth GameObjects need to be on two interacting layers in the collision matrix
The Hearth component needs to be either on the same GameObject with a collider or on the same GameObject with the RigidBody2D
I actually simplified rules 1 and 2 a bit to show the most common use-case: if you want to know the actual rules for collisions, you can find them here (see the matrix at the bottom).
Besides the general collision rules I would make sure your fields have the correct type in the first place and already attach the Heart component to your prefab.
Also there is no need for find .. You already know the reference to the player you are colliding with
public class Chest : MonoBehaviour
{
public Heart heartPrefab;
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
Instantiate(heart, transform.position + Vector3.up * 0.5f), Quaternion.identity);
Destroy(gameObject);
}
}
}
and then simply do
public class Heart : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D col)
{
if (col.TryGetComponent<LifeSystem>(out var ls))
{
SoundManager.PlaySound("CollectCoinSound");
ls.lifes += 1;
Destroy(gameObject);
}
}
}
and rather have the LifeSystem attached to your player object.
In general I would kind of expect both eventually triggered at the same time since the heart might be already triggered if spawning right where the player is

Character Collision problem in unity 2D game

I'm making a 2D game and trying to make a characters move automatically when they spawn from the door to the desk or close to the sofa then stop there. the problem is that they don't collide with anything in the background like sofa or table or desk and they keep going trying to force move and going out of the canvas. this is a GIF for the game play and script that i'm using on the characters:
What am I supposed to do?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterConstantMove : MonoBehaviour
{
GameManager Game_Manager;
void Start()
{
GameObject gameController = GameObject.FindGameObjectWithTag("GameController");
Game_Manager = gameController.GetComponent<GameManager>();
}
void Update()
{
transform.Translate(Game_Manager.moveVector * Game_Manager.moveSpeed * Time.deltaTime);
}
}
GameManager.Cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public float moveSpeed = 1.0f;
public Vector2 moveVector;
}
That's what happens when you translate the body in every frame. From an answer to this similar problem has been addressed, Transform is not a physics-based component. It's the position, rotation, and scale of the object. It doesn't interact with physics system on it's own. Rigidbody is a physics-based component that performs different kinds of physics interactions, like collisions, forces, and more.
Add a rigidbody component to your gameobject and set its velocity, it then interacts with the game physics.
private Rigidbody2D rb;
private void Awake() {
rb = GetComponent<Rigidbody2D>();
}
private void Update() {
rb.velocity = Game_Manager.moveVector * Game_Manager.moveSpeed;
}

OnCollisonEnter2D Unity c# script for 2D collisions not working

I am trying to make a 2d platformer. I have an object that when the player collides with it, the game restarts. For some reason it doesn't work. I set a simple Debug.Log statement to test it. But, it just doesn't work. Here's the code
using UnityEngine;
public class Collision : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collisionInfo)
if (collisionInfo.collider.tag == "Lose")
{
Debug.Log("lose");
}
}
}

C# in Unity, SetActive several gameObjects from player entering trigger area

Brand new to C# and Unity.Please be nice I've been at this all night. Every tutorial I poor through says changing an object from invisible to visible is as simple as setting the game object to on. However Unity gives me an error when I declare a game object in this script. The objective is, when the trigger is entered, several game objects called 'spawn' will become visible.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collider : MonoBehaviour
{
public gameObject Spawn; // I get error On this line that type is expected,
//not property. It wants a Transform>
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void OnTriggerEnter(BoxCollider other)
{
if (other.gameObject.CompareTag("Player"))
{
Spawn.SetActive(true);
}
}
}
gameObject isn't a type, but GameObject is.
Get rid of public gameObject Spawn; and use public GameObject Spawn; to declare a GameObject property called Spawn

Calling a script from NPCs in Unity to trigger dialogue

I have followed Brackeys tutorial on Youtube (https://www.youtube.com/watch?v=_nRzoTzeyxU) on how to create a dialogue system for a game. I am currently attempting to adapt this system to where the player can walk up to an NPC and press the "Submit" button to access their dialogue, instead of clicking a button on the canvas/UI like the video shows. To those who have played games like Super Mario64, The Legend of Zelda: Ocarina of time, or most games with text dialogue you may recognize this.
The Interactable script I created detects whether the player is within the collision sphere or not that the NPC has, and allows the player to press the "Submit" button on what is supposed to call the dialogue for the NPC in range. I'm just not sure how to call the script that I named DialogueTrigger that holds the dialogue for the NPC. That, or what I'm trying to accomplish is not being accomplished in the way that I am trying. Any help would be appreciated.
Interactable Script: `
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Interactable : MonoBehaviour {
private GameObject triggeringNpc;
private bool triggering;
public DialogueTrigger Diag;
void Start()
{
}
void Update()
{
if(triggering)
{
Debug.Log("Within Range");
if (Input.GetButtonDown("Submit"))
{
Debug.Log("Pressed the Interact Button");
Diag.TriggerDialogue();
}
}
}
void OnTriggerEnter(Collider other)
{
if(other.tag == "NPC")
{
triggering = true;
triggeringNpc = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "NPC")
{
triggering = false;
triggeringNpc = null;
}
}
}
`
Right now I can put a script for one NPC in the script and it works, but I would rather it call whatever Dialogue Trigger Script that the NPC has. I'm sure there's something I'm missing here.
This one is for Dialogue Trigger
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
public Dialogue dialogue;
public void TriggerDialogue ()
{
FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
Debug.Log("dm called"); } else { Debug.Log("dm is null"); }
}
}
Solved this as soon as I posted it. Turns out I just needed to combine the Interactable script with the dialogue triggers script and rearranging the collision tags to hit the player that was tagged "Player" rather than having a separate script that detected collision to the NPC.

Categories