- Home /
How modify a game object's collider?
I'm trying to update a collider's center point to no avail. I'm trying
void UpdateColliderCenter()
{
if(colCenters != null)
{
BoxCollider bc = new BoxCollider();
Bounds b = gameObject.collider.bounds;
bc.bounds = b;
Destroy(gameObject.collider);
if(colCenters[curIdx].x != 0 &&
colCenters[curIdx].y != 0 &&
colCenters[curIdx].z != 0)
{
b.center = colCenters[curIdx];
gameObject.AddComponent(bc);
}else
{
b.center = startColCenter;
gameObject.AddComponent(bc);
}
}
}
But I get compiler errors at bc.bound = b; and gameObject.AddComponent(bc); The 1st error is saying that bounds is read only. The other errors state the function only takes strings. Isn't there some way to add a given instance of a component to a game object?
Answer by rutter · Mar 29, 2012 at 03:30 AM
The 1st error is saying that bounds is read only.
It is. You can't edit an objects bounds
property directly. Instead, you can edit the object, and its bounds will naturally change depending on what you've done.
For example, if you know the object has a BoxCollider
attached, you can adjust its size and/or center point like so:
var bc = GetComponent(BoxCollider);
bc.center = Vector3.zero; //move center to local (0,0,0)
bc.size *= 2; //double collider's size
The other errors state the function only takes strings.
I'm not familiar with that error. You'll probably get more help if you copy-paste your specific error message in with your question.
All the posts I found while googling for this also mentioned setting the size property of a collider, but that is read only as well, even if I cast the collider to a Box Collider like (bc as BoxCollider).size, like some posts I found had suggested, it was still read only. Same goes for size's properties (x and y).
I thought I had been getting a read only error when attempting to modify center as well, but that must have been a different issue, because that no longer errors on me.
What I did finally end up finding out was that I need to modify the extents property of a collider ins$$anonymous$$d of size.
Ah, good catch. $$anonymous$$y bad on giving you some questionable information, there. Glad you figured it out, though!