英文:
Unity & C# // How can I change the physical material of the capsule collider to true or false as a Bool value in C#?
问题
我正在使用Unity制作一个小游戏,但我遇到了一个小问题,你能帮我吗?
如何在C#中将胶囊碰撞器的物理材质更改为true或false作为布尔值?
我已经创建了一个物理材质并将其应用于我的玩家的胶囊碰撞器。在C#中,我想通过布尔值手动设置为true或false。
英文:
I'm making a small game with Unity, but I'm having a small problem, can you help me?
How can I change the physical material of the capsule collider to true or false as a Bool value in C#?
I've created a physics material and applied it to my Player's Capsule Collider. In C#, I want to manually set true or false value through bool.
答案1
得分: 0
[SerializeField] PhysicMaterial materialToApply;
[SerializeField] CapsuleCollider colliderToAdjust;
void TogglePhysicsMaterial(bool Toggle)
{
if (Toggle)
{
colliderToAdjust.material = materialToApply;
}
else
{
colliderToAdjust.material = null;
}
}
As others have said, just set the material property to null when you don't want it, and assign it when you do. I saw you want to have it toggle on jump, so here is a quick and dirty way as an example:
void Update()
{
if(colliderToAdjust.transform.position.y > 0
&& !colliderToAdjust.material)
{
TogglePhysicsMaterial(true);
}
else if(colliderToAdjust.transform.position.y <= 0
&& colliderToAdjust.material)
{
TogglePhysicsMaterial(false);
}
}
There are plenty of (MUCH) better ways to handle jump detection (e.g. Raycasts) so please don't think this is a good method as it relies on the capsule being placed at 0 height and wouldn't work with an incline.
英文:
[SerializeField] PhysicMaterial materialToApply;
[SerializeField] CapsuleCollider colliderToAdjust;
void TogglePhysicsMaterial(bool Toggle)
{
if (Toggle)
{
colliderToAdjust.material = materialToApply;
}
else
{
colliderToAdjust.material = null;
}
}
As others have said, just set the material property to null when you don't want it, and assign it when you do. I saw you want to have it toggle on jump, so here is a quick and dirty way as an example:
void Update()
{
if(colliderToAdjust.transform.position.y > 0
&& !colliderToAdjust.material)
{
TogglePhysicsMaterial(true);
}
else if(colliderToAdjust.transform.position.y <= 0
&& colliderToAdjust.material)
{
TogglePhysicsMaterial(false);
}
}
There are plenty of (MUCH) better ways to handle jump detection (e.g. Raycasts) so please don't think this is a good method as it relies on the capsule being placed at 0 height and wouldn't work with an incline.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论