Ok, I’m pretty new to Unity and scripting, so this might be a stupid question.
I made a box that could be pushed around by the player, but I didn’t want it to be pushed around from the top of the box, like when you are standing on it. I wanted to have a trigger activate when you stand on the box that would stop the box moving, but when you get off it, you can still move it back and forth as usual.So, I got it to work, which was great, but I don’t really know why it is working.
I thought the Box Collider 2D’s ‘Is Trigger’ checkbox was the only way to use ‘OnTriggerEnter2D’.
But in this case, I don’t have any “Is Trigger” selected on any of the objects connected to this script, yet it still triggers without them whenever my player(“Sparty”) interacts with a collider.
I tried adding a collider with a trigger and that would also activate the trigger, but the box colliders without triggers would do exactly the same thing.
So then, do you not need “Is Trigger” for the “OnTrigger” functions?
I will show you my code:
using UnityEngine;
using System.Collections;
public class PushableBlock : MonoBehaviour
{
private bool unmoveable = false;
void OnCollisionStay2D(Collision2D other)
{
if (other.gameObject.name == “Sparty” && unmoveable == true)
{
Debug.Log(“working”);
Vector3 spartyScale = other.gameObject.GetComponent().localScale;
if (other.gameObject.GetComponent().localScale.x < 0)
{
//move box to the left.
transform.Translate(-0.01f, 0, 0);
}
if (other.gameObject.GetComponent().localScale.x > 0 && unmoveable == true)
{
//move box to the right.
transform.Translate(0.01f, 0, 0);
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log(“triggered”);
if (other.gameObject.name == “Sparty”)
{
unmoveable = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
Debug.Log(“triggeredOut”);
if (other.gameObject.name == “Sparty”)
{
unmoveable = false;
}
}
}