- Home /
Want to detect if object is in grid.
So I have an object and a script that generates grids. What I want to do is tell me if the object is in a specific area of the grid, and if so for how long. I looked up online for how to detect and found that to approach this with 2D colliders. So I attempted this and played the scene and ultimately it will not work. Is my code wrong. Both the object and the grid have isTrigger box checked on inspector. Just wanted to clarify I am new to unity. Here is the code and a picture of what is happening.
Here is the code for telling if the object is in the grid(The debug also does not show when the object is in grid)
``` using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Collide : MonoBehaviour { bool isInSection1, isInSection2; private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "GridHolder") { isInSection1 = true; isInSection2 = false; Debug.Log("Test");
}
else if (collision.gameObject.name=="eye")
{
isInSection1 = false;
isInSection2 = true;
Debug.Log("Test");
}
}
} ```
Answer by davidcox70 · Aug 10, 2020 at 05:18 PM
Add a rigidbody to your object and a collider set to trigger on the grid. For triggers to work, one of the objects has to have a rigidbody.
the object has a rigidbody 2D already, so this will not work and i have to remove it and replace with rigidbody? Also do i remove box collider for the object and only keep it for grid
If you already had a rigidbody2D, then maybe this isn't the problem. But set it up so you have a rigidbody2D and collider (not set to trigger) on your object, and a collider set to trigger on your grid, and see if that works. If not, report back and we'll look again.
I did that and I still do not receive a debug log when the object is moved to the grid, perhaps something is wrong with my grid? Here is the code for the grid
using System.Collections; using System.Collections.Generic; using UnityEngine; //5,8,1 public class Grid$$anonymous$$anager : $$anonymous$$onoBehaviour { [SerializeField] private int rows = 5; [SerializeField] private int cols = 8; [SerializeField] private float tileSize=1; // Start is called before the first frame update void Start() { GenerateGrid(); }
private void GenerateGrid() { GameObject referenceTile=(GameObject)Instantiate(Resources.Load("GrassTile")); for (int row =0; row
float posX = col * tileSize;
float posY = row * -tileSize;
tile.transform.position = new Vector2(posX, posY);
}
}
Destroy(referenceTile);
float gridW = cols * tileSize;
float gridH = rows * tileSize;
transform.position = new Vector2(-gridW / 2 + tileSize / 2, gridH / 2 - tileSize / 2);
} }
Your answer
Follow this Question
Related Questions
Enemy Detection Area 1 Answer
collision wont work 1 Answer
Collision isn't detected between two obects 1 Answer