Hi I am making my first game in Unity. It is a 2D soccer game. I have a player, soccerball and net. I currently have it so when my soccerball enters the collision box it will print the soccerball is in the net. What I eventually want to do is add 100 points to the score, but I am getting ahead of myself. Right now when my soccerball enters the collision box it does as its supposed to. But unfortunately when I enter the collision box it does the same. What I want is so that when the soccerball enters the net it prints the message not when my player does. So my question is how do I make it so it triggers only when the soccerball touches it not when my player does.
The code is currently:
using UnityEngine;
using System.Collections;
public class Net : MonoBehaviour {
public int score = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D ball)
{
print ("Soccer ball is in the net!!! with print");
}
}
You can use either Physics2D.IgnoreCollision, Physics2D.IgnoreLayerCollision, OR you can go into Edit>Project Settings>Physics 2D and uncheck the checkbox for the pair of layers that you want to ignore collisions over (should you wish to do it via layers).
Alternatively, if you’re using Triggers (as it appears you are), you could simply return after the condition you wanted to determine that the “collision” shouldn’t happen was met. A good way to determine what GameObject is in there is to check the tag, as Landern mentioned. You could, as well, simply keep a reference to the ball, and check against that, since I imagine there would only be one.
To check the tag of a GameObject in your code, you will likely want to do something like this:
void OnTriggerEnter2D(Collider2D other) {
if(other.tag == "tagNameIWantedToDetect")
{
// Do something
}
else
{
// Do something else
}
}
You can set a GameObject’s tag in the editor (on the GameObject, under its “Name” field, in the inspector, select the dropdown menu “tag” and select “AddTag”, and add a new tag), or you can set it programmatically, through the GameObject’s reference, in a script. However, the tag must already exist in the tag manager (accessible through the aforementioned method of setting the tag, or through Edit>Project Settings>Tags & Layers).
Check the ball’s tag or name, if its what youre looking for, do stuff, if not, move on.