1
\$\begingroup\$

I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field.

I check different tutorials and documentation and cannot find a way to do this in code.

My code looks like:

objectToPlace = (GameObject)AssetDatabase.LoadAssetAtPath("Assets/Game/3D Models/Buildings/" + objectName + ".fbx", typeof(GameObject));
objectToPlace.SetActive(true);
objectToPlace.transform.localScale = new Vector3(1, 1, 1);
objectToPlace = Instantiate(objectToPlace);

objectToPlace.transform.Rotate(Vector3.right * 90);

BoxCollider collider = (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider));
collider.isTrigger = true;

In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6?

I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.

\$\endgroup\$
4
  • \$\begingroup\$ I didn't confidered using Physics.Checkbox before. Can you give a small example of using that. When I check for collisions using if (!Physics.CheckBox(objectToPlace.GetComponent<BoxCollider>().center, objectToPlace.GetComponent<BoxCollider>().size/2)) I always getting false \$\endgroup\$ Commented Jun 5, 2017 at 5:28
  • \$\begingroup\$ For now the default values \$\endgroup\$ Commented Jun 5, 2017 at 5:31
  • \$\begingroup\$ When I check also for triggers nothing happend when the two objects collide. Physics.CheckBox(objectToPlace.GetComponent<BoxCollider>().center, objectToPlace.GetComponent<BoxCollider>().size, objectToPlace.transform.rotation, objectToPlace.layer, QueryTriggerInteraction.Collide) \$\endgroup\$ Commented Jun 5, 2017 at 5:47
  • \$\begingroup\$ What is the best sollution to fix this? \$\endgroup\$ Commented Jun 5, 2017 at 5:55

1 Answer 1

1
\$\begingroup\$

I created a custom class for the collision detection with the OnTriggerExit, OnTriggerStay and OnTriggerEnter funtions. Also in my class where I place my models I added:

objectToPlace.AddComponent(typeof(BuildingColliderHandler));
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.