Hello Guest

Author Topic: how to setup colliders programatically  (Read 3692 times)

darebak

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
how to setup colliders programatically
« on: August 07, 2013, 07:01:44 pm »
Hi,
i'm trying to setup collider programatically but so far i didn't succeed. I've tried this:
               
Code: [Select]
                tk2dSpriteCollectionSize sz2 = tk2dSpriteCollectionSize.Default();
_sprite = tk2dSprite.CreateFromTexture(texture, sz2, new Rect(0,0,texture.width, texture.height), new Vector2(0,0));

GameObject go = new GameObject();
MeshCollider collider = go.AddComponent<MeshCollider>();
collider.bounds = new Bounds(new Vector3(0,0,0), new Vector3(10,10,1));

_sprite.collider = collider;

However this doesn't work because _sprite.collider is read only. How can i attach the collider to _sprite? Thanks in advance.

gary-unikronsoftware

  • 2D Toolkit
  • Jr. Member
  • *
  • Posts: 74
    • View Profile
Re: how to setup colliders programatically
« Reply #1 on: August 07, 2013, 09:04:19 pm »
Hi,

Is there any reason why you are using a mesh collider?  It's just that these are for more complex objects and the bounds are calculated based on the mesh of the object.  What you're trying to do is fairly straight forward using a simple box collider, something like:

Code: [Select]
BoxCollider collider;
if(_sprite.GetComponent<BoxCollider>() == null)
{
collider = _sprite.gameObject.AddComponent<BoxCollider>();
}
else
{
collider = _sprite.gameObject.GetComponent<BoxCollider>();
}

collider.center = new Vector3 (0, 0, 0);
collider.size = new Vector3(10,10,1);

Does this help?

darebak

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: how to setup colliders programatically
« Reply #2 on: August 07, 2013, 10:38:23 pm »
I was using mesh collider because i'm new to unity so im still a little bit lost. Your example works perfectly, thanks a lot.